diff --git a/typescript/package-lock.json b/typescript/package-lock.json index 94460d10..d3068be8 100644 --- a/typescript/package-lock.json +++ b/typescript/package-lock.json @@ -30,11 +30,13 @@ "@tree-sitter-grammars/tree-sitter-kotlin": "1.1.0", "@tree-sitter-grammars/tree-sitter-lua": "0.4.1", "@types/node": "^22.10.0", + "@types/pg": "^8.11.10", "@unicode/unicode-15.0.0": "2.1.0", "ai": "^7.0.163", "falkordb": "^7.0.0", "js-tiktoken": "^1.0.21", "kuzu": "^0.11.3", + "pg": "^8.13.1", "tree-sitter-bash": "0.25.1", "tree-sitter-c": "0.24.1", "tree-sitter-c-sharp": "0.24.0", @@ -1989,6 +1991,18 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/pg": { + "version": "8.11.10", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.11.10.tgz", + "integrity": "sha512-LczQUW4dbOQzsH2RQ5qoeJ6qJPdrcM/DcMLoqWQkMLMsq83J5lAX3LXjdkWdpscFy67JSOWDnh7Ny/sPFykmkg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^4.0.1" + } + }, "node_modules/@unicode/unicode-15.0.0": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/@unicode/unicode-15.0.0/-/unicode-15.0.0-2.1.0.tgz", @@ -4254,6 +4268,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/obuf": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", + "integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==", + "dev": true, + "license": "MIT" + }, "node_modules/obug": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", @@ -4333,6 +4354,172 @@ "dev": true, "license": "MIT" }, + "node_modules/pg": { + "version": "8.13.1", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.13.1.tgz", + "integrity": "sha512-OUir1A0rPNZlX//c7ksiu7crsGZTKSOXJPgtNiHGIlC9H0lO+NC6ZDYksSgBYY/thSWhnSRBv8w1lieNNGATNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.7.0", + "pg-pool": "^3.7.0", + "pg-protocol": "^1.7.0", + "pg-types": "^2.1.0", + "pgpass": "1.x" + }, + "engines": { + "node": ">= 8.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.1.1" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz", + "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz", + "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==", + "dev": true, + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-numeric": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pg-numeric/-/pg-numeric-1.0.2.tgz", + "integrity": "sha512-BM/Thnrw5jm2kKLE5uJkXqqExRUY/toLHda65XgFTBTFYZyopbKjBe29Ii3RbkvlsMoFwD+tHeGaCjjv0gHlyw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=4" + } + }, + "node_modules/pg-pool": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz", + "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz", + "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==", + "dev": true, + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-4.1.0.tgz", + "integrity": "sha512-o2XFanIMy/3+mThw69O8d4n1E5zsLhdO+OPqswezu7Z5ekP4hYDqlDjlmOpYMbzY2Br0ufCwJLdDIXeNVwcWFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "pg-numeric": "1.0.2", + "postgres-array": "~3.0.1", + "postgres-bytea": "~3.0.0", + "postgres-date": "~2.1.0", + "postgres-interval": "^3.0.0", + "postgres-range": "^1.1.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pg/node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pg/node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/pg/node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pg/node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pg/node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pgpass": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.6.tgz", + "integrity": "sha512-lqIfH7bdgsxHAY/ZnUOwm+aCFKrsHBDhSFuk9O0B9uCqJAIkrKTo/+LQqLPLUS4e04+jCmQVikxE3QipH5chPw==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -4458,6 +4645,56 @@ } } }, + "node_modules/postgres-array": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.4.tgz", + "integrity": "sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/postgres-bytea": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-3.0.0.tgz", + "integrity": "sha512-CNd4jim9RFPkObHSjVHlVrxoVQXz7quwNFpz7RY1okNNme49+sVyiTvTRobiLV548Hx/hb1BG+iE7h9493WzFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "obuf": "~1.1.2" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/postgres-date": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-2.1.0.tgz", + "integrity": "sha512-K7Juri8gtgXVcDfZttFKVmhglp7epKb1K4pgrkLxehjqkrgPhfG6OO8LHLkfaqkbpjNRnra018XwAr1yQFWGcA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/postgres-interval": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-3.0.0.tgz", + "integrity": "sha512-BSNDnbyZCXSxgA+1f5UU2GmwhoI0aU5yMxRGO8CdFEcY2BQF9xm/7MqKnYoM1nJDk8nONNWDk9WeSmePFhQdlw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/postgres-range": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/postgres-range/-/postgres-range-1.1.4.tgz", + "integrity": "sha512-i/hbxIE9803Alj/6ytL7UHQxRvZkI9O4Sy+J3HGc4F4oo/2eQAjTSNJ0bfxyse3bH0nuVesCk+3IRLaMtG3H6w==", + "dev": true, + "license": "MIT" + }, "node_modules/proxy-addr": { "version": "2.0.8", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", @@ -6109,6 +6346,16 @@ "dev": true, "license": "ISC" }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/typescript/package.json b/typescript/package.json index e01081a2..d2ee6098 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -97,6 +97,7 @@ "falkordb": ">=6", "js-tiktoken": "^1.0.0", "kuzu": ">=0.11", + "pg": ">=8", "tree-sitter-bash": "0.25.1", "tree-sitter-c": "0.24.1", "tree-sitter-c-sharp": "0.24.0", @@ -155,6 +156,9 @@ "kuzu": { "optional": true }, + "pg": { + "optional": true + }, "tree-sitter-bash": { "optional": true }, @@ -221,11 +225,13 @@ "@tree-sitter-grammars/tree-sitter-kotlin": "1.1.0", "@tree-sitter-grammars/tree-sitter-lua": "0.4.1", "@types/node": "^22.10.0", + "@types/pg": "^8.11.10", "@unicode/unicode-15.0.0": "2.1.0", "ai": "^7.0.163", "falkordb": "^7.0.0", "js-tiktoken": "^1.0.21", "kuzu": "^0.11.3", + "pg": "^8.13.1", "tree-sitter-bash": "0.25.1", "tree-sitter-c": "0.24.1", "tree-sitter-c-sharp": "0.24.0", diff --git a/typescript/src/index.ts b/typescript/src/index.ts index 56f130dd..9d640d6c 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -217,5 +217,6 @@ export { CypherPrimitives } from "./stores/cypherPrimitives.js"; export { type FalkorDBSocketOptions, FalkorDBStore, type FalkorDBStoreOptions } from "./stores/falkordb.js"; export { HydraDBStore, type HydraDBStoreOptions } from "./stores/hydradb.js"; export { KuzuStore, type KuzuStoreOptions } from "./stores/kuzu.js"; +export { PgHydraDBStore, type PgHydraDBStoreOptions } from "./stores/pgHydradb.js"; export { type FromTablesOptions, fromTables } from "./tables.js"; export type { ExtractionTier, Level, RerankTier, SeedTier } from "./tiers.js"; diff --git a/typescript/src/stores/pgHydradb.ts b/typescript/src/stores/pgHydradb.ts new file mode 100644 index 00000000..72176e1e --- /dev/null +++ b/typescript/src/stores/pgHydradb.ts @@ -0,0 +1,783 @@ +import type { Pool, PoolConfig } from "pg"; + +import { + connectionReason, + errorReason, + escapeControls, + graphUnavailable, + maskUri, + readOnlyStore, + redactUri, + requireEncodedUserinfo, + SetupError, + STORE_CLOSED_MESSAGE, + StoreError, + TransientError, + unsupportedRead, + ValidationError, +} from "../errors.js"; +import { normalizeRelType, slug } from "../ids.js"; +import { loadOptional } from "../internal/optional.js"; +import { comparePy, pyRepr } from "../internal/py.js"; +import { EDGE_TYPES, L_ENTITY } from "../labels.js"; +import type { CypherResult } from "../models.js"; +import type { + EdgeRow, + GraphPrimitives, + GraphStore, + MatchEdgesOptions, + MatchNodesOptions, + Props, +} from "../protocols.js"; +import { markPartial } from "../retrieval.js"; +import { asSchema, type ParsedSchema } from "../schema.js"; +import { encodeEntityProps, encodeRelationProps } from "../serde.js"; +import { fromTables, words } from "../tables.js"; +import { checkOptions, keysOf } from "../validate.js"; + +const EPOCH = new Date(Date.UTC(1970, 0, 1)); +const NAME_COLUMNS = ["name", "full_name", "display_name", "title", "label", "login", "username"]; +const CASTS: Record = { smallint: "bigint", integer: "bigint", bigint: "bigint", uuid: "uuid" }; +const SEEDS_PER_WALK = 128; +const MAX_EDGES = 5000; +const SEED_TERMS = 16; +const WRITES = + "lockNode upsertNode upsertNodes createEdge createEdges updateCurrentEdge removeNodeLabel deleteNode deleteNodes deleteNodesBy deleteEdges deleteEdgesTouchingByType"; +const GRAPH = "SELECT needs_refresh FROM hydradb.graphs WHERE name = $1"; +const tables = (registry: string, extra: string): string => + `SELECT t.label, n.nspname, c.relname, t.key_column::text AS key, format_type(k.atttypid, NULL) AS key_type, +has_table_privilege(c.oid, 'SELECT') AS readable, ${extra} +FROM hydradb.${registry} t JOIN pg_class c ON c.oid = t.relation JOIN pg_namespace n ON n.oid = c.relnamespace +JOIN pg_attribute k ON k.attrelid = c.oid AND k.attname = t.key_column WHERE t.graph = $1 ORDER BY t.label`; +const VERTEX_TABLES = tables( + "graph_vertex_tables", + "ARRAY(SELECT a.attname::text FROM pg_attribute a WHERE a.attrelid = c.oid AND a.attnum > 0 " + + "AND NOT a.attisdropped AND a.atttypid IN ('text'::regtype, 'varchar'::regtype, 'bpchar'::regtype) " + + "ORDER BY a.attnum) AS text_columns", +); +const EDGE_TABLES = tables( + "graph_edge_tables", + "t.source_column::text AS source, t.source_label, t.target_column::text AS target, t.target_label, " + + "t.kind_column::text AS kind", +); +const WALK = + "SELECT w->'truncated' AS truncated, (SELECT coalesce(jsonb_agg(jsonb_build_array(i->>'label', i->>'key')), " + + "'[]') FROM jsonb_array_elements(w->'items') i) AS items FROM hydradb.reachable_edges($1, $2::jsonb, $3::jsonb) w"; + +export interface PgHydraDBStoreOptions { + graph: string; + names?: Record; + statementTimeout?: number; + seedLimit?: number; + poolSize?: number; + namespace?: string; +} + +const OPTION_KEYS = keysOf({ + graph: true, + names: true, + statementTimeout: true, + seedLimit: true, + poolSize: true, + namespace: true, +}); + +type Row = Record; + +interface Table { + label: string; + prefix: string; + ref: string; + type: string; + key: string; + cast: string; + name?: string | null; + source?: string; + sourceLabel?: string; + target?: string; + targetLabel?: string; + kind?: string | null; +} + +/** + * Quote a Postgres identifier read from the pg_hydradb registry. + * @param name (string): the raw identifier. + * @return (string): the identifier in double quotes, inner quotes doubled. + */ +function ident(name: string): string { + return `"${name.replaceAll('"', '""')}"`; +} + +/** + * Escape the LIKE wildcards and the escape character in text. + * @param text (string): the literal text. + * @return (string): the text, matched literally by ILIKE. + */ +function like(text: string): string { + return text.replace(/([\\%_])/g, "\\$1"); +} + +/** + * Read one key from the text after an id's colon, typed as the key column is. + * @param table (Table): the table. + * @param text (string): the key text. + * @return (string | bigint | null): an integer, a uuid string, or the text; null when the text cannot be a key of this table. + */ +function keyOf(table: Table, text: string): string | bigint | null { + if (table.cast === "bigint") { + const key = /^-?[0-9]{1,19}$/.test(text) ? BigInt(text) : null; + return key !== null && key >= -(2n ** 63n) && key < 2n ** 63n ? key : null; + } + if (table.cast === "uuid") return /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(text) ? text : null; + return text; +} + +/** + * Build the fixed read of some columns of a table's rows. + * @param table (Table): the table. + * @param columns (string): the quoted columns, each cast to text. + * @param where (string): the condition, over bound parameters only. + * @return (string): the statement. + */ +function lookup(table: Table, columns: string, where: string): string { + return `SELECT ${table.key}::text AS k, ${columns} FROM ${table.ref} WHERE ${where}`; +} + +/** + * The condition that keeps the rows whose key is in the JSON array bound as $1. + * @param table (Table): the table. + * @return (string): the condition; one JSON parameter needs no driver array type. + */ +function byKeys(table: Table): string { + return `${table.key} = ANY(ARRAY(SELECT jsonb_array_elements_text($1::jsonb)::${table.cast}))`; +} + +/** + * Describe one registered table from its registry row. + * @param row (Row): the registry row. + * @param type (string): the entity or relation type its rows get. + * @param columns (Partial): the display, endpoint, and kind columns. + * @return (Table): the table. + */ +function describe(row: Row, type: string, columns: Partial
): Table { + return { + label: row.label as string, + prefix: slug(row.label as string), + ref: `${ident(row.nspname as string)}.${ident(row.relname as string)}`, + type, + key: ident(row.key as string), + cast: CASTS[row.key_type as string] ?? "text", + ...columns, + }; +} + +/** + * Report whether a node or edge passes an equality filter and a keyset bound. + * @param props (Props): its properties. + * @param equals (Props | null | undefined): property name to required value. + * @param idGt (string | null | undefined): the id it must sort after, or null. + * @return (boolean): true when it passes. + */ +function keeps(props: Props, equals: Props | null | undefined, idGt: string | null | undefined): boolean { + if (idGt != null && comparePy(props.id as string, idGt) <= 0) return false; + return Object.entries(equals ?? {}).every(([k, v]) => props[k] === v); +} + +/** + * Combine a required id and an id list into the ids to keep, or null for no restriction. + * @param one (string | null | undefined): the one id required, or null. + * @param many (readonly string[] | null | undefined): the ids accepted, or null. + * @return (Set | null): the ids to keep. + */ +function wanted(one: string | null | undefined, many: readonly string[] | null | undefined): Set | null { + if (one == null) return many == null ? null : new Set(many); + return many == null || many.includes(one) ? new Set([one]) : new Set(); +} + +export class PgHydraDBStore implements GraphStore { + private readonly uri: string; + private readonly graph: string; + private readonly names: Record; + private readonly timeoutMs: number; + private readonly seedLimit: number; + private readonly poolSize: number; + private readonly namespace: string; + private pool: Pool | null = null; + private closed = false; + private starting: Promise | null = null; + private vertices = new Map(); + private edges = new Map(); + private draft: Record = {}; + + /** + * A read-only store over tables a pg_hydradb graph registers: rows are entities, edge rows relations. + * @param uri (string): the postgresql URI of a login with SELECT on the graph's tables. + * @param options (PgHydraDBStoreOptions): graph, the pg_hydradb graph name; names, the display-name column per vertex label (a label left out uses its first text column called name, full_name, display_name, title, label, login, or username, else its first text column); statementTimeout, seconds each statement may run (default 10); seedLimit, the most rows one name lookup returns per table and query word (default 200); poolSize, the most connections (default 4); namespace, the one namespace the rows are read under (default "default"). + */ + constructor(uri: string, options: PgHydraDBStoreOptions) { + checkOptions("PgHydraDBStore", options, OPTION_KEYS); + requireEncodedUserinfo(uri); + this.uri = uri; + this.graph = options.graph; + this.names = { ...(options.names ?? {}) }; + this.timeoutMs = Math.max(1, Math.trunc((options.statementTimeout ?? 10) * 1000)); + this.seedLimit = options.seedLimit ?? 200; + this.poolSize = options.poolSize ?? 4; + this.namespace = options.namespace ?? "default"; + } + + /** Connect and read the graph's registration, failing when it is missing, paused, or unreadable. */ + async initialize(): Promise { + if (this.closed) throw new StoreError(STORE_CLOSED_MESSAGE, { code: "store_closed" }); + this.starting ??= this.start().catch((exc) => { + this.starting = null; + throw exc; + }); + await this.starting; + } + + /** Open the pool and read the registry, releasing the pool when that fails so a later call can retry. */ + private async start(): Promise { + const pg = await loadOptional<{ default?: { Pool: typeof Pool }; Pool?: typeof Pool }>( + "pg", + "the postgres store needs pg: npm install pg", + SetupError, + ); + if (this.closed) throw new StoreError(STORE_CLOSED_MESSAGE, { code: "store_closed" }); + const PoolClass = (pg.Pool ?? pg.default?.Pool) as typeof Pool; + const options = `-c default_transaction_read_only=on -c statement_timeout=${this.timeoutMs}`; + const pool = new PoolClass({ connectionString: this.uri, max: this.poolSize, options } as PoolConfig); + pool.on("error", () => {}); + this.pool = pool; + try { + await this.loadRegistry(); + } catch (exc) { + this.pool = null; + await pool.end(); + throw exc; + } + } + + /** + * Check that a read is for the store's namespace, then connect once. + * @param ns (string): the namespace the caller reads. + */ + private async open(ns: string): Promise { + if (ns !== this.namespace) { + throw new ValidationError(`this postgres store serves namespace ${pyRepr(this.namespace)}, not ${pyRepr(ns)}`, { + field: "namespace", + }); + } + await this.initialize(); + } + + /** Read the graph's vertex and edge tables, checking that this login can read each one. */ + private async loadRegistry(): Promise { + [this.vertices, this.edges] = [new Map(), new Map()]; + const found = await this.query(GRAPH, this.graph); + if (!found.length) { + throw graphUnavailable(this.graph, "is not registered; ask the owner to run hydradb.create_graph"); + } + if (found[0]!.needs_refresh != null) { + const reason = escapeControls(found[0]!.needs_refresh as string); + throw graphUnavailable(this.graph, `is paused (${reason}); ask the owner to run hydradb.refresh_graph`); + } + const vertexRows = await this.query(VERTEX_TABLES, this.graph); + const edgeRows = await this.query(EDGE_TABLES, this.graph); + for (const row of [...vertexRows, ...edgeRows]) { + if (!row.readable) { + const table = `${row.nspname}.${row.relname}`; + throw graphUnavailable(this.graph, `cannot be read by this login: grant SELECT on ${table}`); + } + } + const labels = new Set(vertexRows.map((row) => row.label as string)); + const unknown = Object.keys(this.names) + .filter((label) => !labels.has(label)) + .sort(comparePy); + if (unknown.length) { + throw new ValidationError(`names: ${pyRepr(unknown[0])} is not a vertex label of ${pyRepr(this.graph)}`, { + field: "names", + }); + } + const draft = fromTables( + vertexRows.map((row) => ({ name: row.label })), + { name: this.graph }, + ); + const entities = draft.entities.map((entity, i) => { + const row = vertexRows[i]!; + const texts = row.text_columns as string[]; + let name = + (Object.hasOwn(this.names, row.label as string) && this.names[row.label as string]) || + NAME_COLUMNS.find((c) => texts.includes(c)) || + texts[0] || + null; + if (name !== null && !texts.includes(name)) { + throw new ValidationError(`names: ${pyRepr(name)} is not a text column of ${pyRepr(row.relname)}`, { + field: "names", + }); + } + name = name === null ? null : ident(name); + const table = describe(row, entity.name, { name }); + this.vertices.set(table.prefix, table); + const synonyms = [...new Set([...entity.synonyms, words(row.relname as string).join(" ")])]; + return { name: entity.name, synonyms, mappings: [{ table: `${row.nspname}.${row.relname}` }] }; + }); + const relations = new Map(); + for (const row of edgeRows) { + const kind = row.kind == null ? null : ident(row.kind as string); + const table = describe(row, normalizeRelType(row.label as string), { + source: ident(row.source as string), + target: ident(row.target as string), + sourceLabel: row.source_label as string, + targetLabel: row.target_label as string, + kind, + }); + this.edges.set(table.prefix, table); + this.allowed(table.type); + if (kind !== null) continue; + const relation = relations.get(table.type) ?? { type: table.type, from: { types: [] }, to: { types: [] } }; + relations.set(table.type, relation); + for (const [side, label] of [ + ["from", table.sourceLabel], + ["to", table.targetLabel], + ] as const) { + const type = this.vertices.get(slug(label!))!.type; + if (!relation[side].types.includes(type)) relation[side].types.push(type); + } + } + this.draft = { name: this.graph, entities, relations: [...relations.values()] }; + } + + /** + * Draft a schema from the graph's registration: an entity type per vertex label, a relation per edge label. + * + * Types are named from the labels as fromTables names tables, with the table as a synonym and a mapping. An edge + * table with a kind column adds no relation type, since its types are values in its rows. + * @return (ParsedSchema): the draft schema. + */ + async draftSchema(): Promise { + await this.initialize(); + return asSchema(this.draft as never)!; + } + + /** + * Refuse an edge type that Self Graph keeps for its own edges, since reads would hide such relations. + * @param type (string): the relation type of an edge label or kind. + * @return (string): the type; throws StoreError with code graph_unavailable when it is reserved. + */ + private allowed(type: string): string { + if (EDGE_TYPES.has(type)) { + throw graphUnavailable(this.graph, `has edges of type ${pyRepr(type)}, which Self Graph reserves; rename it`); + } + return type; + } + + /** Close the connection pool; later calls throw StoreError. */ + async close(): Promise { + this.closed = true; + this.starting = null; + const pool = this.pool; + this.pool = null; + if (pool !== null) await pool.end(); + } + + /** + * Run one fixed, parameterised read and return its rows, mapping a driver error to a coded one. + * @param query (string): the statement. + * @param args (unknown[]): its parameters. + * @return (Row[]): the rows. + */ + private async fetch(query: string, ...args: unknown[]): Promise { + await this.initialize(); + return this.query(query, ...args); + } + + /** + * Run one statement on the pool, mapping a driver error to a coded one. + * @param query (string): the statement. + * @param args (unknown[]): its parameters. + * @return (Row[]): the rows. + */ + private async query(query: string, ...args: unknown[]): Promise { + if (this.pool === null) throw new StoreError(STORE_CLOSED_MESSAGE, { code: "store_closed" }); + try { + return (await this.pool.query(query, args)).rows; + } catch (exc) { + throw this.error(exc); + } + } + + /** + * Map a driver error to a coded error that never shows the URI's password. + * @param exc (unknown): the driver error. + * @return (StoreError): the error to throw. + */ + error(exc: unknown): StoreError { + const err = exc as { code?: string; severity?: string }; + const state = err?.severity === undefined ? null : (err.code ?? null); + const reason = this.redact(errorReason(exc)); + if (state === null) { + const failure = this.redact(connectionReason(exc)); + return new StoreError(`cannot reach Postgres at ${pyRepr(maskUri(this.uri.split("?")[0]!))}: ${failure}`, { + code: "store_unreachable", + }); + } + if (state === "57014") { + return new TransientError(`Postgres cancelled a query at the statement timeout: ${reason}`, { + code: "store_busy", + }); + } + if (state === "28000" || state === "28P01") { + return new StoreError(`Postgres rejected the login: ${reason}`, { code: "store_auth_failed" }); + } + if (state === "3D000") + return new StoreError(`Postgres has no such database: ${reason}`, { code: "database_not_found" }); + if (state === "42501") return graphUnavailable(this.graph, `cannot be read by this login: ${reason}`); + if (["3F000", "42P01", "42883"].includes(state)) { + return graphUnavailable(this.graph, "is unavailable: pg_hydradb is not installed in this database"); + } + if (reason.includes("unknown graph")) { + return graphUnavailable(this.graph, "is not registered; ask the owner to run hydradb.create_graph"); + } + if (reason.includes("refresh_graph") || reason.includes("row-level security")) { + return graphUnavailable(this.graph, `cannot be queried: ${reason}`); + } + return new StoreError(`Postgres rejected a query: ${reason}`, { code: "query_failed" }); + } + + /** + * Hide the URI's user, password, and any password query parameter in a driver message. + * @param text (string): the message. + * @return (string): the message with control characters escaped and credentials replaced by ***. + */ + private redact(text: string): string { + let out = redactUri(text, this.uri); + for (const [, secret] of this.uri.matchAll(/[?&]password=([^&#]+)/g)) { + out = out.replaceAll(secret!, "***").replaceAll(decodeURIComponent(secret!), "***"); + } + return escapeControls(out); + } + + /** + * Group ids by the registered table their prefix names, as typed keys, dropping ids of no table. + * @param tablesBy (Map): the vertex or edge tables by id prefix. + * @param ids (Iterable): the ids, without the "relation:" prefix of a relation id. + * @return (Map>): each table prefix with its keys, in first-seen order. + */ + private keys(tablesBy: Map, ids: Iterable): Map> { + const keys = new Map>(); + for (const id of new Set(ids)) { + const at = id.indexOf(":"); + const prefix = at < 0 ? id : id.slice(0, at); + const table = tablesBy.get(prefix); + const key = table === undefined || at < 0 ? null : keyOf(table, id.slice(at + 1)); + if (key === null) continue; + const group = keys.get(prefix) ?? []; + if (!group.length) keys.set(prefix, group); + group.push(key); + } + return keys; + } + + /** + * Encode one vertex row as an entity's stored properties. + * @param ns (string): namespace. + * @param table (Table): the vertex table. + * @param key (string): the row key as text. + * @param name (string | null): the display name, or null to show the key. + * @return (Props): the entity properties. + */ + private entity(ns: string, table: Table, key: string, name: string | null): Props { + return encodeEntityProps({ + ns, + id: `${table.prefix}:${key}`, + type: table.type, + name: name?.trim() ? name : key, + aliases: [], + external_ids: {}, + properties: {}, + source_count: 1, + created_at: EPOCH, + updated_at: EPOCH, + }); + } + + /** + * Read vertex rows by id, one key lookup per table. + * @param ns (string): namespace. + * @param ids (Iterable): entity ids. + * @return (Props[]): the entities found, as stored properties. + */ + private async nodes(ns: string, ids: Iterable): Promise { + await this.open(ns); + const found: Props[] = []; + for (const [prefix, keys] of this.keys(this.vertices, ids)) { + const t = this.vertices.get(prefix)!; + const query = lookup(t, t.name === null ? "NULL AS n" : `${t.name}::text AS n`, byKeys(t)); + for (const row of await this.fetch(query, JSON.stringify(keys.map(String)))) { + found.push(this.entity(ns, t, row.k as string, row.n as string | null)); + } + } + return found; + } + + /** + * Read the rows whose display name holds a query word, a bounded lookup per table and word. + * @param ns (string): namespace. + * @param terms (readonly string[]): the query words. + * @return (Props[]): the matching entities, as stored properties. + */ + async seedCandidates(ns: string, terms: readonly string[]): Promise { + const sorted = [...new Set(terms)].sort(comparePy).slice(0, SEED_TERMS); + return this.named( + ns, + sorted.map((t) => `%${like(t)}%`), + ); + } + + /** + * Read the rows whose display name holds the words of a folded-name match key, for entity lookups. + * @param ns (string): namespace. + * @param keys (Iterable): match keys; only "form:" keys apply, as rows have no aliases or external ids. + * @return (Props[]): the candidate entities, as stored properties. + */ + async entitiesMatching(ns: string, keys: Iterable): Promise { + const forms = [ + ...new Set([...keys].filter((k) => k.startsWith("form:") && k.slice(5).trim()).map((k) => k.slice(5))), + ]; + forms.sort(comparePy); + const patterns = [ + ...forms.map(like), + ...forms.map((f) => `%${f.split(/\s+/).filter(Boolean).map(like).join("%")}%`), + ]; + return this.named(ns, patterns); + } + + /** + * Run the fixed ILIKE lookup on each table's display column, one pattern per statement. + * @param ns (string): namespace. + * @param patterns (string[]): ILIKE patterns with literal text escaped. + * @return (Props[]): the matching entities, as stored properties, each once. + */ + private async named(ns: string, patterns: string[]): Promise { + await this.open(ns); + const found = new Map(); + for (const t of this.vertices.values()) { + if (t.name === null) continue; + const query = lookup(t, `${t.name}::text AS n`, `${t.name} ILIKE $1 LIMIT $2`); + for (const pattern of patterns) { + for (const row of await this.fetch(query, pattern, this.seedLimit)) { + const props = this.entity(ns, t, row.k as string, row.n as string | null); + found.set(props.id as string, props); + } + } + } + return [...found.values()]; + } + + /** + * Fetch one row as an entity by id. + * @param ns (string): namespace. + * @param label (string): node label; only Entity has rows. + * @param id (string): entity id, ":". + * @return (Props | null): the entity properties, or null. + */ + async getNode(ns: string, label: string, id: string): Promise { + const found = label === L_ENTITY ? await this.nodes(ns, [id]) : []; + return found[0] ?? null; + } + + async nodeExists(ns: string, label: string, id: string): Promise { + return (await this.getNode(ns, label, id)) !== null; + } + + /** + * Return the rows with the given ids as entities; a read with no id list is refused. + * @param ns (string): namespace. + * @param label (string): node label; only Entity has rows. + * @param options (MatchNodesOptions): any_of must hold only "id"; equals, skip, limit, and id_gt filter and page. + * @return (Props[]): entity properties, in id order. + */ + async matchNodes(ns: string, label: string, options: MatchNodesOptions = {}): Promise { + if (label !== L_ENTITY) return []; + const anyOf = options.any_of ?? {}; + if (Object.keys(anyOf).length !== 1 || !("id" in anyOf)) throw unsupportedRead("list every entity"); + const rows = (await this.nodes(ns, anyOf.id as string[])).filter((p) => keeps(p, options.equals, options.id_gt)); + rows.sort((a, b) => comparePy(a.id as string, b.id as string)); + const skip = options.skip ?? 0; + return rows.slice(skip, skip + (options.limit ?? 1000)); + } + + /** + * List the edges one hop from the seeds with reachable_edges, halving the seeds when a walk is cut short. + * @param seeds (Array<[string, string | bigint]>): (vertex label, key) pairs, at most SEEDS_PER_WALK. + * @param direction (string): "outgoing" or "incoming". + * @return (string[][]): the reached edges as [label, key text]; marks the read partial when one seed alone is cut. + */ + private async walk(seeds: Array<[string, string | bigint]>, direction: string): Promise { + const grouped = new Map(); + for (const [label, key] of seeds) { + grouped.set(label, [...(grouped.get(label) ?? []), typeof key === "bigint" ? `${key}` : JSON.stringify(key)]); + } + const json = `{${[...grouped].map(([label, keys]) => `${JSON.stringify(label)}: [${keys.join(", ")}]`).join(", ")}}`; + const options = { max_depth: 1, direction, max_edges: MAX_EDGES, max_sources: SEEDS_PER_WALK }; + const [result] = await this.fetch(WALK, this.graph, json, JSON.stringify(options)); + if ((result!.truncated as string[]).some((reason) => reason !== "depth")) { + if (seeds.length > 1) { + const half = Math.floor(seeds.length / 2); + return [ + ...(await this.walk(seeds.slice(0, half), direction)), + ...(await this.walk(seeds.slice(half), direction)), + ]; + } + markPartial(); + } + return result!.items as string[][]; + } + + /** + * Read every edge one hop from some entities, a walk per batch of rows and a key lookup per edge table. + * @param ns (string): namespace. + * @param ids (string[]): the entity ids. + * @param direction (string): "outgoing" or "incoming". + * @return (EdgeRow[]): the edges. + */ + private async adjacent(ns: string, ids: string[], direction: string): Promise { + await this.open(ns); + const seeds: Array<[string, string | bigint]> = []; + for (const [prefix, keys] of this.keys(this.vertices, ids)) { + for (const k of keys) seeds.push([this.vertices.get(prefix)!.label, k]); + } + const items: string[][] = []; + for (let at = 0; at < seeds.length; at += SEEDS_PER_WALK) { + items.push(...(await this.walk(seeds.slice(at, at + SEEDS_PER_WALK), direction))); + } + const prefixes = new Map([...this.edges.values()].map((t) => [t.label, t.prefix])); + return this.edgeRows( + ns, + items.map(([label, k]) => `relation:${prefixes.get(label)}:${k}`), + ); + } + + /** + * Read edge rows by relation id, one key lookup per table. + * @param ns (string): namespace. + * @param ids (Iterable): relation ids, "relation::". + * @return (EdgeRow[]): the edges. + */ + private async edgeRows(ns: string, ids: Iterable): Promise { + await this.open(ns); + const found: EdgeRow[] = []; + for (const [prefix, keys] of this.keys( + this.edges, + [...ids].map((id) => (id.startsWith("relation:") ? id.slice(9) : id)), + )) { + const t = this.edges.get(prefix)!; + const kind = t.kind === null ? "NULL" : `${t.kind}::text`; + const query = lookup(t, `${t.source}::text AS s, ${t.target}::text AS t, ${kind} AS kind`, byKeys(t)); + for (const row of await this.fetch(query, JSON.stringify(keys.map(String)))) { + const props = encodeRelationProps({ + ns, + id: `relation:${t.prefix}:${row.k}`, + revision: 1, + properties: {}, + event_time: null, + created_at: EPOCH, + is_current: true, + source_count: 1, + }); + found.push({ + props, + from_id: `${slug(t.sourceLabel!)}:${row.s}`, + to_id: `${slug(t.targetLabel!)}:${row.t}`, + type: row.kind ? this.allowed(normalizeRelType(row.kind as string)) : t.type, + }); + } + } + return found; + } + + /** + * Return the edges out of or into given entities, walked in pg_hydradb; a read with no endpoint is refused. + * @param ns (string): namespace. + * @param options (MatchEdgesOptions): from_label (only Entity has edges), to_label, type, from_id, to_id, from_in, to_in, equals, skip, limit, and id_gt; every edge row is current. + * @return (EdgeRow[]): the edges, in id order. + */ + async matchEdges(ns: string, options: MatchEdgesOptions): Promise { + if (options.from_label !== L_ENTITY || (options.to_label != null && options.to_label !== L_ENTITY)) return []; + const froms = wanted(options.from_id, options.from_in); + const tos = wanted(options.to_id, options.to_in); + if (froms === null && tos === null) throw unsupportedRead("list every relation"); + const [start, direction] = froms !== null ? [froms, "outgoing"] : [tos!, "incoming"]; + const rows = (await this.adjacent(ns, [...start].sort(comparePy), direction)).filter( + (e) => + (froms === null || froms.has(e.from_id)) && + (tos === null || tos.has(e.to_id)) && + (options.type == null || e.type === options.type) && + keeps(e.props, options.equals, options.id_gt), + ); + const order = (e: EdgeRow): string[] => [e.props.id as string, e.from_id, e.to_id]; + rows.sort((a, b) => { + const [x, y] = [order(a), order(b)]; + return comparePy(x[0]!, y[0]!) || comparePy(x[1]!, y[1]!) || comparePy(x[2]!, y[2]!); + }); + const skip = options.skip ?? 0; + return rows.slice(skip, skip + (options.limit ?? 1000)); + } + + /** + * Fetch one edge row by relation id. + * @param ns (string): namespace. + * @param id (string): relation id, "relation::". + * @return (EdgeRow | null): the edge, or null. + */ + async getCurrentEdge(ns: string, id: string): Promise { + return (await this.edgeRows(ns, [id]))[0] ?? null; + } + + async listEdgeVersions(ns: string, id: string): Promise { + return this.edgeRows(ns, [id]); + } + + async childNodes(): Promise { + return []; + } + + async countNodesByNs(): Promise> { + throw unsupportedRead("count every row"); + } + + async countEdgesByNs(): Promise> { + throw unsupportedRead("count every row"); + } + + async runCypher(): Promise { + throw unsupportedRead("run Cypher"); + } + + async transaction(_fn: (tx: GraphPrimitives) => Promise): Promise { + throw readOnlyStore("a write transaction"); + } + + declare lockNode: GraphPrimitives["lockNode"]; + declare upsertNode: GraphPrimitives["upsertNode"]; + declare upsertNodes: GraphPrimitives["upsertNodes"]; + declare createEdge: GraphPrimitives["createEdge"]; + declare createEdges: GraphPrimitives["createEdges"]; + declare updateCurrentEdge: GraphPrimitives["updateCurrentEdge"]; + declare removeNodeLabel: GraphPrimitives["removeNodeLabel"]; + declare deleteNode: GraphPrimitives["deleteNode"]; + declare deleteNodes: GraphPrimitives["deleteNodes"]; + declare deleteNodesBy: GraphPrimitives["deleteNodesBy"]; + declare deleteEdges: GraphPrimitives["deleteEdges"]; + declare deleteEdgesTouchingByType: GraphPrimitives["deleteEdgesTouchingByType"]; +} + +for (const method of WRITES.split(" ")) { + const primitive = method.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`); + Object.defineProperty(PgHydraDBStore.prototype, method, { + value: async () => { + throw readOnlyStore(primitive); + }, + }); +} diff --git a/typescript/src/tables.ts b/typescript/src/tables.ts index 641c54df..7319d550 100644 --- a/typescript/src/tables.ts +++ b/typescript/src/tables.ts @@ -32,7 +32,7 @@ interface DraftRelation { * @param name (string): the name, such as sales.invoice_lines or InvoiceLines. * @return (string[]): the words. */ -function words(name: string): string[] { +export function words(name: string): string[] { return Array.from(spaced(name.slice(name.lastIndexOf(".") + 1)).matchAll(WORD), (m) => lower(m[0])); } diff --git a/typescript/test/pgHydradbStore.test.ts b/typescript/test/pgHydradbStore.test.ts new file mode 100644 index 00000000..6212ccb0 --- /dev/null +++ b/typescript/test/pgHydradbStore.test.ts @@ -0,0 +1,200 @@ +import { randomUUID } from "node:crypto"; +import { readFileSync } from "node:fs"; + +import pg from "pg"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { PgHydraDBStore, SelfGraph, StoreError } from "../src/index.js"; + +const OWNER_URI = process.env.SG_PG_HYDRADB_URI ?? process.env.PG_HYDRADB_URI; +const PROJECT = "3f2b8c1e-8f5c-4c2a-9d7e-1a2b3c4d5e6f"; +const SETUP = readFileSync(new URL("../../tests/fixtures/pg_hydradb_work.sql", import.meta.url), "utf8"); +const setup = (s: string): string => SETUP.replaceAll("__SCHEMA__", s).replaceAll("__PROJECT__", PROJECT); + +async function owner(sql: string, params: unknown[] = []): Promise[]> { + const client = new pg.Client({ connectionString: OWNER_URI }); + await client.connect(); + try { + const result = await client.query(sql, params.length ? params : undefined); + return (Array.isArray(result) ? result.at(-1) : result).rows; + } finally { + await client.end(); + } +} + +async function codeOf(call: () => Promise): Promise { + try { + await call(); + } catch (exc) { + if (exc instanceof StoreError) return exc.code; + throw exc; + } + throw new Error("no error"); +} + +it("a password in the uri query stays out of errors", () => { + const store = new PgHydraDBStore("postgresql://127.0.0.1:1/app?user=reader&password=s3cr%23et", { graph: "work" }); + const refused = store.error(Object.assign(new Error("refused"), { code: "ECONNREFUSED", errno: -111 })); + const rejected = store.error( + Object.assign(new Error("password s3cr#et and s3cr%23et"), { code: "28P01", severity: "FATAL" }), + ); + expect(refused.message).toBe("cannot reach Postgres at 'postgresql://127.0.0.1:1/app': connection refused"); + expect(() => new PgHydraDBStore("postgresql://reader:sec/ret@db/app", { graph: "work" })).toThrow( + "unencoded character", + ); + expect([rejected.code, rejected.message]).toEqual([ + "store_auth_failed", + "Postgres rejected the login: password *** and ***", + ]); +}); + +describe.skipIf(!OWNER_URI)("PgHydraDBStore", () => { + let name = ""; + let reader = ""; + const graphs: SelfGraph[] = []; + const open = (options = {}): SelfGraph => { + const g = new SelfGraph(new PgHydraDBStore(reader, { graph: name, ...options })); + graphs.push(g); + return g; + }; + + beforeEach(async () => { + name = `sg_${randomUUID().replaceAll("-", "").slice(0, 10)}`; + await owner(setup(name)); + const url = new URL(OWNER_URI!); + url.username = name; + url.password = `pw-${name}`; + reader = url.toString(); + }); + + afterEach(async () => { + for (const g of graphs.splice(0)) await g.close(); + await owner(`SELECT hydradb.drop_graph('${name}'); DROP SCHEMA ${name} CASCADE; DROP ROLE ${name};`); + }); + + it("retrieve from a question finds the rows that answer it", async () => { + const result = await open().retrieve("who works at Acme"); + expect(result.seeds[0]!.id).toBe("company:acme"); + expect(result.context).toContain("GRAPH | Ann Lee -[WORKS_AT]-> Acme"); + expect(result.context).toContain("GRAPH | ChloƩ Durand -[WORKS_AT]-> Acme"); + expect(result.seeds.map((s) => s.id)).not.toContain("company:globex"); + expect("truncated" in result).toBe(false); + }); + + it("entity ids, neighbors, paths, and the schema draft read the tables", async () => { + const g = open(); + expect((await g.entities.get("person:4"))!.name).toBe("4"); + expect((await g.entities.get(`project:${PROJECT}`))!.type).toBe("Project"); + const seeded = await g.retrieve(null, { entity_ids: ["person:1"], depth: 1 }); + expect(new Set(seeded.subgraph.entities.map((e) => e.id))).toEqual( + new Set(["person:1", "person:2", "company:acme", `project:${PROJECT}`]), + ); + const near = await g.neighbors("person:3"); + expect(near.neighbors.map((n) => [n.entity.id, n.distance])).toEqual([["company:acme", 1]]); + expect(new Set(near.relations.map((r) => r.id))).toEqual(new Set(["relation:works_at:12", "relation:mentors:21"])); + const path = await g.findPath("person:2", "company:acme", { direction: "both" }); + expect(path.steps.map((s) => [s.relation.type, s.entity.id])).toEqual([ + ["MENTORS", "person:1"], + ["WORKS_AT", "company:acme"], + ]); + expect((await g.relations.get("relation:works_at:10"))!.to_entity).toBe("company:acme"); + const schema = await (g.store as PgHydraDBStore).draftSchema(); + expect(schema.entities.map((e) => e.name)).toEqual(["Company", "Person", "Project"]); + const worksAt = schema.relations.find((r) => r.type === "WORKS_AT")!; + expect([worksAt.from.types, worksAt.to.types]).toEqual([["Person"], ["Company"]]); + }); + + it("a row the application writes shows up on the next read", async () => { + const g = open(); + expect((await g.retrieve("who works at Globex")).context).not.toContain("Dana"); + await owner( + `INSERT INTO ${name}.people VALUES (5, 'Dana Wu'); INSERT INTO ${name}.employment VALUES (13, 5, 'globex')`, + ); + expect((await g.retrieve("who works at Globex")).context).toContain("GRAPH | Dana Wu -[WORKS_AT]-> Globex"); + }); + + it("writes and full scans are refused with a code", async () => { + const g = open(); + expect(await codeOf(() => g.entities.create("Eve", "Person"))).toBe("read_only_store"); + expect(await codeOf(() => g.insert.facts({ entities: [{ type: "Person", name: "Eve" }] }))).toBe("read_only_store"); + expect(await codeOf(() => g.store.upsertNode("default", "Entity", "person:9", {}))).toBe("read_only_store"); + expect(await codeOf(() => g.entities.list())).toBe("unsupported_read"); + expect(await codeOf(() => g.runCypher("MATCH (n) RETURN n"))).toBe("unsupported_read"); + const grants = await owner( + "SELECT DISTINCT privilege_type FROM information_schema.role_table_grants WHERE grantee = $1", + [name], + ); + expect(grants.map((row) => row.privilege_type)).toEqual(["SELECT"]); + }); + + it("a missing, paused, or unreadable graph fails to connect", async () => { + expect(await codeOf(() => new PgHydraDBStore(reader, { graph: "no_such_graph" }).initialize())).toBe( + "graph_unavailable", + ); + await owner(`REVOKE SELECT ON ${name}.projects FROM ${name}`); + const denied = await open() + .store.initialize() + .catch((exc: StoreError) => exc); + expect([(denied as StoreError).code, (denied as StoreError).message]).toEqual([ + "graph_unavailable", + `pg_hydradb graph '${name}' cannot be read by this login: grant SELECT on ${name}.projects`, + ]); + await owner( + `GRANT SELECT ON ${name}.projects TO ${name}; ALTER TABLE ${name}.people ALTER COLUMN full_name TYPE text USING upper(full_name)`, + ); + const paused = await open() + .store.initialize() + .catch((exc: StoreError) => exc); + expect((paused as StoreError).code).toBe("graph_unavailable"); + expect((paused as StoreError).message).toContain("is paused"); + }); + + it("edge cases of keys, labels, names, and first use", async () => { + const [top, low] = [2n ** 63n - 1n, -(2n ** 63n)]; + await owner( + `CREATE TABLE ${name}.big (id bigint PRIMARY KEY, name text); CREATE TABLE ${name}.relation (id bigint PRIMARY KEY, name text); + CREATE TABLE ${name}.link (id bigint PRIMARY KEY, a bigint NOT NULL REFERENCES ${name}.big, b bigint NOT NULL REFERENCES ${name}.relation); + INSERT INTO ${name}.big VALUES (${top}, 'Top'), (${low}, 'Low'); INSERT INTO ${name}.relation VALUES (1, 'Rel'); + INSERT INTO ${name}.link VALUES (${top}, ${top}, 1); INSERT INTO ${name}.people SELECT g, 'Annabelle ' || g FROM generate_series(50, 52) g; + INSERT INTO ${name}.people VALUES (53, 'Ann'); GRANT SELECT ON ALL TABLES IN SCHEMA ${name} TO ${name}; + SELECT hydradb.create_graph('${name}_x', '[{"label": "big", "table": "${name}.big", "key": "id"}, + {"label": "relation", "table": "${name}.relation", "key": "id"}]', '[{"label": "relation", "table": "${name}.link", + "key": "id", "source": "a", "source_label": "big", "target": "b", "target_label": "relation"}]')`, + ); + const g = new SelfGraph(new PgHydraDBStore(reader, { graph: `${name}_x` })); + graphs.push(g); + expect((await g.entities.get(`big:${low}`))!.name).toBe("Low"); + expect((await g.neighbors(`big:${top}`)).neighbors.map((n) => n.entity.id)).toEqual(["relation:1"]); + expect((await g.relations.get(`relation:relation:${top}`))!.to_entity).toBe("relation:1"); + expect(await g.entities.get(`big:${top + 1n}`)).toBeNull(); + await expect(new SelfGraph(g.store, { namespace: "tenant-b" }).entities.get(`big:${low}`)).rejects.toThrow( + "serves namespace 'default', not 'tenant-b'", + ); + const people = open({ seedLimit: 2 }); + expect((await people.entities.find("Ann")).map((m) => m.entity.id)).toEqual(["person:53"]); + const later = new PgHydraDBStore(reader, { graph: `${name}_y` }); + expect(await codeOf(() => later.initialize())).toBe("graph_unavailable"); + await owner( + `SELECT hydradb.create_graph('${name}_y', '[{"label": "person", "table": "${name}.people", "key": "id"}]', + '[{"label": "prefers", "table": "${name}.mentorships", "key": "id", "source": "mentor_id", + "source_label": "person", "target": "mentee_id", "target_label": "person"}]')`, + ); + await expect(later.initialize()).rejects.toThrow("'PREFERS', which Self Graph reserves"); + const fresh = new PgHydraDBStore(reader, { graph: name }); + const found = await Promise.all([1, 2, 3, 53].map((i) => fresh.getNode("default", "Entity", `person:${i}`))); + expect(found.map((p) => p!.name)).toEqual(["Ann Lee", "Bob Stone", "ChloƩ Durand", "Ann"]); + await fresh.close(); + for (const g of graphs.splice(0)) await g.close(); + await owner(`SELECT hydradb.drop_graph('${name}_x'); SELECT hydradb.drop_graph('${name}_y')`); + }); + + it("a walk cut by pg_hydradb marks the result truncated", async () => { + await owner(`INSERT INTO ${name}.people SELECT g, 'P' || g FROM generate_series(100, 5200) g`); + await owner(`INSERT INTO ${name}.employment SELECT g, g, 'globex' FROM generate_series(100, 5200) g`); + const g = open(); + const near = await g.neighbors("company:globex", { limit: 10_000 }); + expect(near.truncated).toBe(true); + expect(near.neighbors.length).toBeGreaterThanOrEqual(5000); + expect((await g.neighbors("company:acme")).truncated).toBe(false); + }); +});