From 514253751559aa48209ed1c9bea4e74ccfacb6ab Mon Sep 17 00:00:00 2001 From: Arinjay Wyawhare <72088094+jaywyawhare@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:08:08 +0530 Subject: [PATCH 1/2] Generate typed models from schemas --- docs/cli.md | 1 + docs/schema.md | 42 +++++++ src/selfgraph/cli.py | 11 +- src/selfgraph/schema_codegen.py | 160 +++++++++++++++++++++++++ tests/test_schema_codegen.py | 145 ++++++++++++++++++++++ typescript/src/cli.ts | 11 +- typescript/src/index.ts | 1 + typescript/src/schema.ts | 10 +- typescript/src/schemaCodegen.ts | 159 ++++++++++++++++++++++++ typescript/test/conformance/py_side.py | 19 ++- typescript/test/conformance/ts_side.ts | 15 +++ typescript/test/schemaCodegen.test.ts | 159 ++++++++++++++++++++++++ 12 files changed, 725 insertions(+), 8 deletions(-) create mode 100644 src/selfgraph/schema_codegen.py create mode 100644 tests/test_schema_codegen.py create mode 100644 typescript/src/schemaCodegen.ts create mode 100644 typescript/test/schemaCodegen.test.ts diff --git a/docs/cli.md b/docs/cli.md index f4177561..d55fc807 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -85,6 +85,7 @@ settings from the environment are ignored silently. | `version` | Prints the installed version as JSON. `--version` or `-V` prints it bare. | | `mcp` | Runs the [MCP](mcp.md) server over stdio with the global flags, or over streamable HTTP with `--transport http`, `--host`, `--port`, and `--token` ([over HTTP](mcp.md#over-http)). `--read-only` serves only the read tools. | | `install` | Adds the MCP server to an agent's config. See [`install`](#install). | +| `schema codegen FILE` | Emits [typed models](schema.md#generating-typed-models) in the CLI's SDK language. `-` reads schema JSON from stdin. | | `schema from-tables FILE` | Drafts schema JSON from table metadata, reading no rows and opening no connection. `-` reads stdin. | | `schema` | Prints the active schema, or `null` with a hint on stderr. `schema import FILE` and `schema export` convert from and to a [Neo4j graph schema](schema.md#neo4j-graph-schema-interop); `schema export --to ossie` prints an [Apache Ossie ontology](schema.md#apache-ossie-export). `schema suggest` [suggests a schema](schema.md#suggesting-a-schema-from-the-graph) from the stored types, with `--extend`, `--min-count N`, and `--format selfgraph` or `neo4j`. Importing a file that is already a SelfGraph schema fails with a hint to pass it as `--schema`. | | `readiness` | Prints whether the store is reachable and the namespace holds data, with counts (also by entity and relation type) and lint ([readiness](trust.md#readiness)). | diff --git a/docs/schema.md b/docs/schema.md index 5a2b1c27..e448ba81 100644 --- a/docs/schema.md +++ b/docs/schema.md @@ -15,6 +15,48 @@ The schema defines types; stored items only name them. `EntityType` and are the plain type names on stored items, such as `"Person"` or `"WORKS_AT"`. Without a schema, any name is accepted. +## Generating typed models + +Run `selfgraph schema codegen schema.json > graph_models.py` with the Python +CLI, or `selfgraph schema codegen schema.json > graph-models.ts` with the +TypeScript CLI. Pass `-` to read schema JSON from stdin. Code generation +also works from the SDK via `selfgraph.schema_codegen.generate_schema_types` +in Python or `generateSchemaTypes` in TypeScript. + +Each entity or relation has a model and a corresponding property type. +Properties include inherited declarations. Required keys need a non-null +value, and date and time properties use ISO 8601 strings. The generated +identifiers use letters and digits from the schema type names, with numeric +suffixes for collisions. The helpers use the stored type name and the original +property keys. + +This example uses a schema that declares `Person` with a required integer `age`. + +```python +from graph_models import Person + +created = await Person.create(graph, "Ada", {"age": 42}) +person = await Person.get(graph, created.id) +if person is not None: + age: int = person.properties["age"] +``` + +```typescript +import { Person } from "./graph-models.js"; + +const created = await Person.create(graph, "Ada", { age: 42 }); +const person = await Person.get(graph, created.id); +const age = person?.properties.age; +``` + +Use the same schema to configure the graph and generate its models. Relation +helpers take the source ID, destination ID, and properties. The generated +`create` returns the SDK's full record. The generated `get` returns the ID, +type, name or endpoints, and typed properties, or null (`None` in Python) for +a missing record or a different type. Invalid properties raise `schema_violation` +through these helpers even when the graph uses warning mode. Regenerate the +module when the schema changes. + ## Defining one Pass a `Schema`, or a dict with the same shape, to the graph or to one insert. diff --git a/src/selfgraph/cli.py b/src/selfgraph/cli.py index 6f99b56f..42422d1d 100644 --- a/src/selfgraph/cli.py +++ b/src/selfgraph/cli.py @@ -63,6 +63,7 @@ sync_glob, ) from .schema import ContradictionMode, Schema, SchemaMode +from .schema_codegen import generate_schema_types from .tiers import LADDERS, LEVELS __all__ = ["main", "build_parser"] @@ -90,6 +91,7 @@ _LOGGED_WARNINGS = ("basic_extraction", "ner_extraction") _SCHEMA_HELP = """schema: print the active schema (--schema FILE), or null schema import [--from neo4j] FILE: convert a Neo4j graph schema +schema codegen FILE: generate Python models from schema JSON schema from-tables FILE: draft a schema from table metadata without reading rows or opening a connection schema export [--to neo4j|ossie]: print the active schema as a Neo4j graph schema or an Apache Ossie ontology schema suggest [--extend] [--min-count N] [--format selfgraph|neo4j]: suggest a schema from the stored types""" @@ -411,6 +413,10 @@ def _inserted(result: Any) -> Any: return result +async def _schema_codegen(graph, args): + return _Text(generate_schema_types(read_json(args.path, "path")).removesuffix("\n")) + + async def _schema_from_tables(graph, args): return Schema.from_tables(read_json(args.path, "path")) @@ -860,6 +866,9 @@ def build_parser() -> argparse.ArgumentParser: ) sc.set_defaults(func=_schema) sca = sc.add_subparsers(dest="schema_action") + cg = sca.add_parser("codegen", help="generate Python models from schema JSON, or '-' for stdin") + cg.add_argument("path") + cg.set_defaults(func=_schema_codegen) st = sca.add_parser("from-tables", help="draft a schema from table metadata JSON, or '-' for stdin") st.add_argument("path") st.set_defaults(func=_schema_from_tables) @@ -1641,7 +1650,7 @@ async def _run_with_diagnostics(args: argparse.Namespace, settings: GraphSetting logger.addHandler(handler) logger.setLevel(logging.INFO) try: - if args.command in ("version", "check-citations") or args.func is _schema_from_tables: + if args.command in ("version", "check-citations") or args.func in (_schema_from_tables, _schema_codegen): return await dispatch(None, args) graph = build_graph(settings) try: diff --git a/src/selfgraph/schema_codegen.py b/src/selfgraph/schema_codegen.py new file mode 100644 index 00000000..37dc4858 --- /dev/null +++ b/src/selfgraph/schema_codegen.py @@ -0,0 +1,160 @@ +import re +from collections.abc import Mapping +from typing import Literal + +from ._ops import _clean_text, _require_json_mapping +from .errors import ValidationError +from .ids import normalize_rel_type +from .models import JsonValue +from .schema import PropertySpec, Schema, _check_properties, _entity_index, _property_specs, as_schema + +__all__ = ["generate_schema_types", "check_generated_properties"] + +_TYPES = { + "string": "str", + "integer": "int", + "float": "float", + "boolean": "bool", + "datetime": "str", + "json": "str | int | float | bool | list[JsonValue] | dict[str, JsonValue]", +} +_RESERVED = { + "Entity", + "Exclude", + "False", + "JsonValue", + "Literal", + "None", + "NotRequired", + "Promise", + "PropertySpec", + "Record", + "Relation", + "SelfGraph", + "True", + "TypedDict", +} + + +def check_generated_properties( + kind: Literal["entity", "relation"], + ref: str, + properties: Mapping[str, object], + specs: list[PropertySpec], +) -> dict[str, JsonValue]: + """Validate generated model properties and convert whole numbers declared as integers to int. + + @param kind (str): the record kind. + @param ref (str): the record ID or type being created. + @param properties (Mapping[str, object]): the properties to validate. + @param specs (list[PropertySpec]): the generated property declarations. + @return (dict): the validated properties. + """ + checked = _require_json_mapping("properties", properties) or {} + warnings = _check_properties(kind, ref, checked, specs) + if warnings: + raise ValidationError("; ".join(warning.message for warning in warnings), code="schema_violation") + return checked + + +def _symbol(name: str, used: set[str]) -> str: + """Allocate a Python model name and reserve its property type. + + @param name (str): the declared schema type name. + @param used (set[str]): the names already reserved in the generated module. + @return (str): the generated model name. + """ + base = "".join( + word.capitalize() if word.isupper() else word[0].upper() + word[1:] + for word in re.findall(r"[A-Za-z0-9]+", name) + ) + if not base or base[0].isdigit(): + base = f"Type{base}" + symbol, suffix = base, 2 + while symbol in used or f"{symbol}Properties" in used: + symbol = f"{base}{suffix}" + suffix += 1 + used.update((symbol, f"{symbol}Properties")) + return symbol + + +def _render(symbol: str, name: str, kind: Literal["entity", "relation"], specs: list[PropertySpec]) -> str: + """Render one model and its typed access methods. + + @param symbol (str): the generated model name. + @param name (str): the stored schema type. + @param kind (str): the record kind. + @param specs (list[PropertySpec]): the effective property declarations. + @return (str): the Python source for the model. + """ + props = f"{symbol}Properties" + fields = [] + for spec in specs: + annotation = _TYPES[spec.type] + if not spec.required: + annotation = f"NotRequired[{annotation} | None]" + fields.append(f" {spec.name!r}: {annotation},") + fields_literal = "{\n" + "\n".join(fields) + "\n}" if fields else "{}" + declarations = [ + f" PropertySpec(name={spec.name!r}, type={spec.type!r}, required={spec.required})," for spec in specs + ] + property_specs = "[\n" + "\n".join(declarations) + "\n]" if declarations else "[]" + entity = kind == "entity" + resource, record = ("entities", "Entity") if entity else ("relations", "Relation") + identity = " name: str" if entity else " from_entity: str\n to_entity: str" + arguments = "name: str" if entity else "from_entity: str, to_entity: str" + create_args = f"name, {name!r}" if entity else f"from_entity, {name!r}, to_entity" + read_args = "value.name" if entity else "value.from_entity, value.to_entity" + return f"""{props} = TypedDict({props!r}, {fields_literal}) +_{symbol}_specs: list[PropertySpec] = {property_specs} + + +@dataclass +class {symbol}: + id: str + type: Literal[{name!r}] +{identity} + properties: {props} + + @staticmethod + async def create(graph: SelfGraph, {arguments}, properties: {props}) -> {record}: + checked = check_generated_properties({kind!r}, {name!r}, properties, _{symbol}_specs) + return await graph.{resource}.create({create_args}, properties=checked) + + @staticmethod + async def get(graph: SelfGraph, id: str) -> "{symbol} | None": + value = await graph.{resource}.get(id) + if value is None or value.type != {name!r}: + return None + checked = check_generated_properties({kind!r}, id, value.properties, _{symbol}_specs) + return {symbol}(value.id, {name!r}, {read_args}, cast({props}, checked))""" + + +def generate_schema_types(schema: Schema | Mapping) -> str: + """Generate an importable Python module from a declared schema. + + @param schema (Schema | Mapping): the schema or its JSON mapping. + @return (str): the Python source, with a trailing newline. + """ + parsed = as_schema(schema) + if parsed is None: + raise ValidationError("schema codegen needs a schema", code="schema_required", field="schema") + index = _entity_index(parsed) + used = _RESERVED.copy() + models = [ + _render(_symbol(entity.name, used), _clean_text(entity.name), "entity", _property_specs(entity, index)) + for entity in parsed.entities + ] + models.extend( + _render(_symbol(relation.type, used), normalize_rel_type(relation.type), "relation", relation.properties) + for relation in parsed.relations + ) + header = ( + "from dataclasses import dataclass\n" + "from typing import Literal, cast\n\n" + "from typing_extensions import NotRequired, TypedDict\n\n" + "from selfgraph import PropertySpec, SelfGraph\n" + "from selfgraph.models import Entity, JsonValue, Relation\n" + "from selfgraph.schema_codegen import check_generated_properties" + ) + return "\n\n\n".join([header, *models]) + "\n" if models else "__all__ = []\n" diff --git a/tests/test_schema_codegen.py b/tests/test_schema_codegen.py new file mode 100644 index 00000000..e1a5cabb --- /dev/null +++ b/tests/test_schema_codegen.py @@ -0,0 +1,145 @@ +import asyncio +import io +import json +import sys +from importlib.util import module_from_spec, spec_from_file_location + +import pytest + +import selfgraph.cli as cli +from selfgraph import KuzuStore, Schema, SelfGraph, ValidationError +from selfgraph.schema_codegen import generate_schema_types + +SCHEMA = { + "entities": [{"name": "Person", "properties": [{"name": "age", "type": "integer", "required": True}]}], + "relations": [{"type": "knows", "properties": [{"name": "since-date", "type": "datetime"}]}], +} + + +def test_schema_codegen_cli_golden(tmp_path, capsys, monkeypatch): + def no_connection(*args, **kwargs): + pytest.fail("code generation opened a store") + + monkeypatch.setattr(cli, "build_graph", no_connection) + path = tmp_path / "schema.json" + path.write_text(json.dumps(SCHEMA)) + for source in (str(path), "-"): + monkeypatch.setattr("sys.stdin", io.StringIO(json.dumps(SCHEMA))) + assert cli.main(["schema", "codegen", source]) == 0 + assert capsys.readouterr().out == GOLDEN + assert generate_schema_types(Schema.model_validate(SCHEMA)) == GOLDEN + + +def test_generated_models_roundtrip(tmp_path, monkeypatch): + schema = { + "entities": [ + {"name": "Being", "properties": [{"name": "age", "type": "integer", "required": True}]}, + {"name": "Person", "parent": "Being"}, + {"name": "Person Properties", "properties": [{"name": "metadata", "type": "json"}]}, + ], + "relations": [{"type": "person", "properties": [{"name": "since-date", "type": "datetime", "required": True}]}], + } + path = tmp_path / "generated.py" + path.write_text(generate_schema_types(schema)) + spec = spec_from_file_location("generated", path) + generated = module_from_spec(spec) + monkeypatch.setitem(sys.modules, "generated", generated) + spec.loader.exec_module(generated) + person = generated.Person + knows = generated.Person2 + assert person.__annotations__["properties"].__required_keys__ == {"age"} + assert generated.PersonProperties2.__annotations__["properties"].__optional_keys__ == {"metadata"} + + async def exercise(): + store = KuzuStore(str(tmp_path / "codegen.kuzu")) + async with SelfGraph(store, schema=schema, schema_mode="off") as graph: + with pytest.raises(ValidationError, match="missing required property 'age'") as rejected: + await person.create(graph, "Rejected", {}) + assert rejected.value.code == "schema_violation" + assert await graph.entities.get("person:rejected") is None + ada = await person.create(graph, "Ada", {"age": 42}) + bea = await graph.entities.create("Bea", "Person", properties={"age": 37.0}) + assert (await person.get(graph, ada.id)).properties == {"age": 42} + assert type((await person.get(graph, bea.id)).properties["age"]) is int + assert await person.get(graph, "person:missing") is None + parent = await graph.entities.create("Parent", "Being", properties={"age": 70}) + assert await person.get(graph, parent.id) is None + legacy = await graph.entities.create("Legacy", "Person") + with pytest.raises(ValidationError, match="missing required property 'age'"): + await person.get(graph, legacy.id) + with pytest.raises(ValidationError, match="should be datetime"): + await knows.create(graph, ada.id, bea.id, {"since-date": "invalid"}) + edge = await knows.create(graph, ada.id, bea.id, {"since-date": "2024-05-01"}) + assert (await knows.get(graph, edge.id)).properties == {"since-date": "2024-05-01"} + + asyncio.run(exercise()) + + +GOLDEN = """from dataclasses import dataclass +from typing import Literal, cast + +from typing_extensions import NotRequired, TypedDict + +from selfgraph import PropertySpec, SelfGraph +from selfgraph.models import Entity, JsonValue, Relation +from selfgraph.schema_codegen import check_generated_properties + + +PersonProperties = TypedDict('PersonProperties', { + 'age': int, +}) +_Person_specs: list[PropertySpec] = [ + PropertySpec(name='age', type='integer', required=True), +] + + +@dataclass +class Person: + id: str + type: Literal['Person'] + name: str + properties: PersonProperties + + @staticmethod + async def create(graph: SelfGraph, name: str, properties: PersonProperties) -> Entity: + checked = check_generated_properties('entity', 'Person', properties, _Person_specs) + return await graph.entities.create(name, 'Person', properties=checked) + + @staticmethod + async def get(graph: SelfGraph, id: str) -> "Person | None": + value = await graph.entities.get(id) + if value is None or value.type != 'Person': + return None + checked = check_generated_properties('entity', id, value.properties, _Person_specs) + return Person(value.id, 'Person', value.name, cast(PersonProperties, checked)) + + +KnowsProperties = TypedDict('KnowsProperties', { + 'since-date': NotRequired[str | None], +}) +_Knows_specs: list[PropertySpec] = [ + PropertySpec(name='since-date', type='datetime', required=False), +] + + +@dataclass +class Knows: + id: str + type: Literal['KNOWS'] + from_entity: str + to_entity: str + properties: KnowsProperties + + @staticmethod + async def create(graph: SelfGraph, from_entity: str, to_entity: str, properties: KnowsProperties) -> Relation: + checked = check_generated_properties('relation', 'KNOWS', properties, _Knows_specs) + return await graph.relations.create(from_entity, 'KNOWS', to_entity, properties=checked) + + @staticmethod + async def get(graph: SelfGraph, id: str) -> "Knows | None": + value = await graph.relations.get(id) + if value is None or value.type != 'KNOWS': + return None + checked = check_generated_properties('relation', id, value.properties, _Knows_specs) + return Knows(value.id, 'KNOWS', value.from_entity, value.to_entity, cast(KnowsProperties, checked)) +""" diff --git a/typescript/src/cli.ts b/typescript/src/cli.ts index f581b595..3b1478ff 100644 --- a/typescript/src/cli.ts +++ b/typescript/src/cli.ts @@ -87,7 +87,8 @@ import { syncFiles, version, } from "./runtime.js"; -import { CONTRADICTION_MODES, type ContradictionMode, SCHEMA_MODES } from "./schema.js"; +import { CONTRADICTION_MODES, type ContradictionMode, SCHEMA_MODES, type Schema } from "./schema.js"; +import { generateSchemaTypes } from "./schemaCodegen.js"; import { fromTables } from "./tables.js"; import { LEVELS, RERANK_TIERS, SEED_TIERS } from "./tiers.js"; import { parseTime } from "./validate.js"; @@ -1265,6 +1266,7 @@ export function buildParser(): Command<[], GlobalOptions> { .description( "schema: print the active schema (--schema FILE), or null\n" + "schema import [--from neo4j] FILE: convert a Neo4j graph schema\n" + + "schema codegen FILE: generate TypeScript models from schema JSON\n" + "schema from-tables FILE: draft a schema from table metadata without reading rows or opening a connection\n" + "schema export [--to neo4j|ossie]: print the active schema as a Neo4j graph schema or an Apache Ossie ontology\n" + "schema suggest [--extend] [--min-count N] [--format selfgraph|neo4j]: suggest a schema from the stored types", @@ -1275,6 +1277,13 @@ export function buildParser(): Command<[], GlobalOptions> { return g.schema; }), ); + schema + .command("codegen ") + .description("generate TypeScript models from schema JSON, or '-' for stdin") + .action((path, _o, cmd) => { + connectSettings(cmd); + return writeOut(generateSchemaTypes(readJson(path) as Schema)); + }); schema .command("from-tables ") .description("draft a schema from table metadata JSON, or '-' for stdin") diff --git a/typescript/src/index.ts b/typescript/src/index.ts index d155e325..1c619848 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -196,6 +196,7 @@ export { type SchemaMode, TermMapping, } from "./schema.js"; +export { checkGeneratedProperties, generateSchemaTypes } from "./schemaCodegen.js"; export { CypherStore, type CypherStoreOptions, Neo4jStore } from "./stores/cypher.js"; export { CypherPrimitives } from "./stores/cypherPrimitives.js"; export { type FalkorDBSocketOptions, FalkorDBStore, type FalkorDBStoreOptions } from "./stores/falkordb.js"; diff --git a/typescript/src/schema.ts b/typescript/src/schema.ts index 2cf3dce9..9dbe9ede 100644 --- a/typescript/src/schema.ts +++ b/typescript/src/schema.ts @@ -140,7 +140,7 @@ export type Schema = z.input; export type ParsedSchema = z.output; type ParsedEntityType = z.output; type ParsedRelationType = z.output; -type ParsedPropertySpec = z.output; +export type ParsedPropertySpec = z.output; type ParsedEndpoint = z.output; const entityRef = (ent: { id: string | null; type: string; name: string }): string => @@ -516,7 +516,7 @@ export function* lineage(entity: ParsedEntityType, index: Map): the entity type index. * @return (ParsedPropertySpec[]): own specs first, then each ancestor's specs not already declared. */ -function propertySpecs(entity: ParsedEntityType, index: Map): ParsedPropertySpec[] { +export function propertySpecs(entity: ParsedEntityType, index: Map): ParsedPropertySpec[] { const specs = new Map(); for (const current of lineage(entity, index)) { for (const spec of current.properties) if (!specs.has(spec.name)) specs.set(spec.name, spec); @@ -556,14 +556,14 @@ function typeOk(value: unknown, expected: PropertyType): boolean { * @param kind (string): the object kind for messages. * @param ref (string): the instance identifier for messages. * @param properties (Record): the instance properties. - * @param specs (readonly ParsedPropertySpec[]): the declared specs. + * @param specs (readonly Pick[]): the declared specs. * @return (InsertWarning[]): the warnings. */ -function checkProperties( +export function checkProperties( kind: string, ref: string, properties: Record, - specs: readonly ParsedPropertySpec[], + specs: readonly Pick[], ): InsertWarning[] { const warnings: InsertWarning[] = []; for (const spec of specs) { diff --git a/typescript/src/schemaCodegen.ts b/typescript/src/schemaCodegen.ts new file mode 100644 index 00000000..f4d16152 --- /dev/null +++ b/typescript/src/schemaCodegen.ts @@ -0,0 +1,159 @@ +import { ValidationError } from "./errors.js"; +import { normalizeRelType } from "./ids.js"; +import type { JsonObject } from "./models.js"; +import { cleanText } from "./ops.js"; +import { + asSchema, + checkProperties, + entityIndex, + type ParsedPropertySpec, + type PropertyType, + propertySpecs, + type Schema, +} from "./schema.js"; +import { requireJsonMapping } from "./validate.js"; + +const TYPES: Record = { + string: "string", + integer: "number", + float: "number", + boolean: "boolean", + datetime: "string", + json: "Exclude", +}; +const RESERVED = [ + "Entity", + "Exclude", + "False", + "JsonValue", + "Literal", + "None", + "NotRequired", + "Promise", + "PropertySpec", + "Record", + "Relation", + "SelfGraph", + "True", + "TypedDict", +]; +type Kind = "entity" | "relation"; +interface GeneratedPropertySpec { + name: string; + type: PropertyType; + required: boolean; +} + +/** + * Validate the properties of a generated model. + * @param kind (Kind): the record kind. + * @param ref (string): the record ID or type being created. + * @param properties (JsonObject): the properties to validate. + * @param specs (GeneratedPropertySpec[]): the generated property declarations. + * @return (JsonObject): the validated properties. + */ +export function checkGeneratedProperties( + kind: Kind, + ref: string, + properties: JsonObject, + specs: readonly GeneratedPropertySpec[], +): JsonObject { + requireJsonMapping("properties", properties); + const checked = properties ?? {}; + const warnings = checkProperties(kind, ref, checked, specs); + if (warnings.length) + throw new ValidationError(warnings.map((warning) => warning.message).join("; "), { code: "schema_violation" }); + return checked; +} + +function allocateSymbol(name: string, used: Set): string { + const words = name.match(/[A-Za-z0-9]+/g) ?? []; + let base = words + .map((word) => word[0]!.toUpperCase() + (word === word.toUpperCase() ? word.slice(1).toLowerCase() : word.slice(1))) + .join(""); + if (!base || /^[0-9]/.test(base)) base = `Type${base}`; + let symbol = base; + for (let suffix = 2; used.has(symbol) || used.has(`${symbol}Properties`); suffix++) symbol = `${base}${suffix}`; + used.add(symbol); + used.add(`${symbol}Properties`); + return symbol; +} + +function render(symbol: string, name: string, kind: Kind, specs: readonly ParsedPropertySpec[]): string { + const storedType = JSON.stringify(name); + const props = `${symbol}Properties`; + const fields = specs.map((spec) => { + const key = JSON.stringify(spec.name); + return spec.required ? ` ${key}: ${TYPES[spec.type]};` : ` ${key}?: ${TYPES[spec.type]} | null;`; + }); + const properties = fields.length ? `{\n${fields.join("\n")}\n}` : "Record"; + const declarations = specs.map(({ name, type, required }) => ` ${JSON.stringify({ name, type, required })},`); + const propertySpecs = declarations.length ? `[\n${declarations.join("\n")}\n]` : "[]"; + const entity = kind === "entity"; + const resource = entity ? "entities" : "relations"; + const record = entity ? "Entity" : "Relation"; + const identity = entity ? " name: string;" : " from_entity: string;\n to_entity: string;"; + const args = entity ? "name: string" : "from_entity: string, to_entity: string"; + const createArgs = entity ? `name, ${storedType}` : `from_entity, ${storedType}, to_entity`; + const readFields = entity ? "name: value.name" : "from_entity: value.from_entity, to_entity: value.to_entity"; + return `export type ${props} = ${properties}; +const _${symbol}Specs = ${propertySpecs} as const; + +export interface ${symbol} { + id: string; + type: ${storedType}; +${identity} + properties: ${props}; +} + +export const ${symbol} = { + async create(graph: SelfGraph, ${args}, properties: ${props}): Promise<${record}> { + const checked = checkGeneratedProperties("${kind}", ${storedType}, properties, _${symbol}Specs); + return graph.${resource}.create(${createArgs}, { properties: checked }); + }, + async get(graph: SelfGraph, id: string): Promise<${symbol} | null> { + const value = await graph.${resource}.get(id); + if (value === null || value.type !== ${storedType}) return null; + const checked = checkGeneratedProperties("${kind}", id, value.properties, _${symbol}Specs); + return { id: value.id, type: value.type, ${readFields}, properties: checked as ${props} }; + }, +};`; +} + +/** + * Generate an importable TypeScript module from a declared schema. + * @param schema (Schema): the schema or its JSON mapping. + * @return (string): the TypeScript source, with a trailing newline. + */ +export function generateSchemaTypes(schema: Schema): string { + const parsed = asSchema(schema); + if (parsed === null) + throw new ValidationError("schema codegen needs a schema", { code: "schema_required", field: "schema" }); + const index = entityIndex(parsed); + const used = new Set(RESERVED); + const blocks = [ + ...parsed.entities.map((entity) => ({ + name: entity.name, + storedType: cleanText(entity.name), + kind: "entity" as const, + specs: propertySpecs(entity, index), + })), + ...parsed.relations.map((relation) => ({ + name: relation.type, + storedType: normalizeRelType(relation.type), + kind: "relation" as const, + specs: relation.properties, + })), + ]; + const types = ["type SelfGraph"]; + if (parsed.entities.length) types.push("type Entity"); + if (parsed.relations.length) types.push("type Relation"); + if (blocks.some(({ specs }) => !specs.length || specs.some((spec) => spec.type === "json"))) { + types.push("type JsonValue"); + } + const models = blocks.map(({ name, storedType, kind, specs }) => + render(allocateSymbol(name, used), storedType, kind, specs), + ); + const header = `import { checkGeneratedProperties, ${types.join(", ")} } from "@hydradb/selfgraph";`; + return models.length ? `${[header, ...models].join("\n\n")}\n` : "export {};\n"; +} diff --git a/typescript/test/conformance/py_side.py b/typescript/test/conformance/py_side.py index 8507b764..cc7dc065 100644 --- a/typescript/test/conformance/py_side.py +++ b/typescript/test/conformance/py_side.py @@ -90,7 +90,8 @@ sync_glob, to_jsonable, ) -from selfgraph.schema import validate_against_schema +from selfgraph.schema import PropertySpec, validate_against_schema +from selfgraph.schema_codegen import check_generated_properties from selfgraph.stores.kuzu import _kuzu_error from selfgraph.terms import expand_tokens, schema_forms @@ -775,6 +776,19 @@ def dropped_extracted_items(): return {"extraction": to_jsonable(facts), "warnings": to_jsonable(warnings)} +def generated_property_outcome(properties): + """Validate generated relation properties and return the value or the coded error. + + @param properties (dict): the candidate properties. + @return (dict): the checked properties or error code and message. + """ + specs = [PropertySpec(name="since-date", type="datetime", required=True)] + try: + return check_generated_properties("relation", "KNOWS", properties, specs) + except ValidationError as exc: + return {"code": exc.code, "message": str(exc)} + + def schema_warnings(): """Validate each schema case and return its warnings as code and message pairs, plus unknown-key errors. @@ -932,6 +946,9 @@ def endpoint_outcome(spec): "schema_dump_roundtrip": to_jsonable( Schema.model_validate({"relations": [{"type": "X", "from_": {"types": ["A"], "max_count": 1}}]}) ), + "generated_properties": [ + generated_property_outcome(value) for value in ({}, {"since-date": "bad"}, {"since-date": "2024-05-01"}) + ], "schema_types": [ unknown_key_error("schema", spec) for value in ("false", 0, 1) diff --git a/typescript/test/conformance/ts_side.ts b/typescript/test/conformance/ts_side.ts index 156079be..97d60953 100644 --- a/typescript/test/conformance/ts_side.ts +++ b/typescript/test/conformance/ts_side.ts @@ -50,6 +50,7 @@ import type { } from "../../src/index.js"; import { checkCitations, + checkGeneratedProperties, FalkorDBStore, fromNeo4jOntology, fromTables, @@ -84,6 +85,7 @@ import { EntityInput, Extraction, type InsertWarning, + type JsonObject, PreferenceInput, parseOrThrow, RelationInput, @@ -847,6 +849,7 @@ export function schemaWarnings(): { integer_properties: Array>; unknown_keys: string[]; schema_dump_roundtrip: unknown; + generated_properties: unknown[]; schema_types: string[]; alias_errors: string[]; consistency_errors: Array<{ code: string; field: string | null; message: string }>; @@ -1071,6 +1074,18 @@ export function schemaWarnings(): { schema_dump_roundtrip: toJsonable( parseOrThrow(Schema, { relations: [{ type: "X", from_: { types: ["A"], max_count: 1 } }] }, "schema"), ), + generated_properties: ([{}, { "since-date": "bad" }, { "since-date": "2024-05-01" }] as JsonObject[]).map( + (properties) => { + try { + return checkGeneratedProperties("relation", "KNOWS", properties, [ + { name: "since-date", type: "datetime", required: true }, + ]); + } catch (error) { + if (!(error instanceof ValidationError)) throw error; + return { code: error.code, message: error.message }; + } + }, + ), schema_types: ["false", 0, 1].flatMap((value) => [ { entities: [{ name: "T", certified: value }] }, diff --git a/typescript/test/schemaCodegen.test.ts b/typescript/test/schemaCodegen.test.ts new file mode 100644 index 00000000..0e6ddb58 --- /dev/null +++ b/typescript/test/schemaCodegen.test.ts @@ -0,0 +1,159 @@ +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import ts from "typescript"; +import { expect, it } from "vitest"; + +import { generateSchemaTypes, KuzuStore, SelfGraph } from "../src/index.js"; +import { runCli, tempDir, tempKuzu } from "./helpers.js"; + +const schema = { + entities: [{ name: "Person", properties: [{ name: "age", type: "integer", required: true }] }], + relations: [{ type: "knows", properties: [{ name: "since-date", type: "datetime" }] }], +} satisfies Parameters[0]; + +it("generates the TypeScript module from schema JSON without a connection", () => { + const dir = tempDir("sg-codegen-"); + const path = join(dir, "schema.json"); + writeFileSync(path, JSON.stringify(schema)); + const source = generateSchemaTypes(schema); + expect(source).toMatchInlineSnapshot(` + "import { checkGeneratedProperties, type SelfGraph, type Entity, type Relation } from "@hydradb/selfgraph"; + + export type PersonProperties = { + "age": number; + }; + const _PersonSpecs = [ + {"name":"age","type":"integer","required":true}, + ] as const; + + export interface Person { + id: string; + type: "Person"; + name: string; + properties: PersonProperties; + } + + export const Person = { + async create(graph: SelfGraph, name: string, properties: PersonProperties): Promise { + const checked = checkGeneratedProperties("entity", "Person", properties, _PersonSpecs); + return graph.entities.create(name, "Person", { properties: checked }); + }, + async get(graph: SelfGraph, id: string): Promise { + const value = await graph.entities.get(id); + if (value === null || value.type !== "Person") return null; + const checked = checkGeneratedProperties("entity", id, value.properties, _PersonSpecs); + return { id: value.id, type: value.type, name: value.name, properties: checked as PersonProperties }; + }, + }; + + export type KnowsProperties = { + "since-date"?: string | null; + }; + const _KnowsSpecs = [ + {"name":"since-date","type":"datetime","required":false}, + ] as const; + + export interface Knows { + id: string; + type: "KNOWS"; + from_entity: string; + to_entity: string; + properties: KnowsProperties; + } + + export const Knows = { + async create(graph: SelfGraph, from_entity: string, to_entity: string, properties: KnowsProperties): Promise { + const checked = checkGeneratedProperties("relation", "KNOWS", properties, _KnowsSpecs); + return graph.relations.create(from_entity, "KNOWS", to_entity, { properties: checked }); + }, + async get(graph: SelfGraph, id: string): Promise { + const value = await graph.relations.get(id); + if (value === null || value.type !== "KNOWS") return null; + const checked = checkGeneratedProperties("relation", id, value.properties, _KnowsSpecs); + return { id: value.id, type: value.type, from_entity: value.from_entity, to_entity: value.to_entity, properties: checked as KnowsProperties }; + }, + }; + " + `); + for (const input of [path, "-"]) { + expect( + runCli(["schema", "codegen", input], { + input: JSON.stringify(schema), + env: { SELFGRAPH_STORE: "kuzu", SELFGRAPH_URI: "/dev/null/unreachable" }, + }), + ).toEqual({ code: 0, err: "", out: source }); + } +}); + +it("type checks generated writes and reads validated models through the graph", async () => { + const spec = { + entities: [ + { name: "Being", properties: [{ name: "age", type: "integer", required: true }] }, + { name: "Person", parent: "Being" }, + { name: "Person Properties", properties: [{ name: "metadata", type: "json" }] }, + ], + relations: [{ type: "person", properties: [{ name: "since-date", type: "datetime", required: true }] }], + } satisfies Parameters[0]; + const source = generateSchemaTypes(spec); + const path = join(tempDir("sg-generated-"), "models.ts"); + writeFileSync( + path, + `${source} +export async function check(graph: SelfGraph) { + // @ts-expect-error age is required + await Person.create(graph, "Ada", {}); + // @ts-expect-error age must be a number + await Person.create(graph, "Ada", {age: "42"}); + // @ts-expect-error the relation property is required + await Person2.create(graph, "person:ada", "person:bea", {}); + const person = await Person.get(graph, "person:ada"); + const age: number | undefined = person?.properties.age; + return age; +} +`, + ); + const sdkTypes = fileURLToPath(new URL("../dist/index.d.ts", import.meta.url)); + const program = ts.createProgram([path], { + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + target: ts.ScriptTarget.ES2022, + strict: true, + exactOptionalPropertyTypes: true, + noUnusedLocals: true, + skipLibCheck: true, + types: [], + paths: { "@hydradb/selfgraph": [sdkTypes] }, + }); + expect( + ts.getPreEmitDiagnostics(program).map((item) => ts.flattenDiagnosticMessageText(item.messageText, "\n")), + ).toEqual([]); + const sdk = new URL("../dist/index.js", import.meta.url).href; + const { outputText } = ts.transpileModule(source.replace('"@hydradb/selfgraph"', JSON.stringify(sdk)), { + compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 }, + }); + const { Person, Person2 } = await import(`data:text/javascript,${encodeURIComponent(outputText)}`); + const graph = new SelfGraph(new KuzuStore(tempKuzu("sg-codegen-graph-")), { schema: spec, schema_mode: "off" }); + try { + await expect(Person.create(graph, "Rejected", {})).rejects.toMatchObject({ code: "schema_violation" }); + expect(await graph.entities.get("person:rejected")).toBeNull(); + const ada = await Person.create(graph, "Ada", { age: 42 }); + const bea = await graph.entities.create("Bea", "Person", { properties: { age: 37 } }); + expect(await Person.get(graph, ada.id)).toMatchObject({ type: "Person", properties: { age: 42 } }); + expect(await Person.get(graph, "person:missing")).toBeNull(); + const parent = await graph.entities.create("Parent", "Being", { properties: { age: 70 } }); + expect(await Person.get(graph, parent.id)).toBeNull(); + const legacy = await graph.entities.create("Legacy", "Person"); + await expect(Person.get(graph, legacy.id)).rejects.toMatchObject({ code: "schema_violation" }); + await expect(Person2.create(graph, ada.id, bea.id, { "since-date": "invalid" })).rejects.toMatchObject({ + code: "schema_violation", + }); + const edge = await Person2.create(graph, ada.id, bea.id, { "since-date": "2024-05-01" }); + expect(await Person2.get(graph, edge.id)).toMatchObject({ + type: "PERSON", + properties: { "since-date": "2024-05-01" }, + }); + } finally { + await graph.close(); + } +}); From 5eaf489a223da638e8c508d09a369fb020f7c7b3 Mon Sep 17 00:00:00 2001 From: Arinjay Wyawhare <72088094+jaywyawhare@users.noreply.github.com> Date: Sat, 5 Dec 2026 06:05:35 +0530 Subject: [PATCH 2/2] Run the codegen round trip on the configured test store --- tests/test_schema_codegen.py | 48 +++++++++++++++++------------------- 1 file changed, 23 insertions(+), 25 deletions(-) diff --git a/tests/test_schema_codegen.py b/tests/test_schema_codegen.py index e1a5cabb..4080a87f 100644 --- a/tests/test_schema_codegen.py +++ b/tests/test_schema_codegen.py @@ -1,13 +1,13 @@ -import asyncio import io import json import sys from importlib.util import module_from_spec, spec_from_file_location import pytest +from helpers import fresh_graph, run import selfgraph.cli as cli -from selfgraph import KuzuStore, Schema, SelfGraph, ValidationError +from selfgraph import Schema, ValidationError from selfgraph.schema_codegen import generate_schema_types SCHEMA = { @@ -50,29 +50,27 @@ def test_generated_models_roundtrip(tmp_path, monkeypatch): assert person.__annotations__["properties"].__required_keys__ == {"age"} assert generated.PersonProperties2.__annotations__["properties"].__optional_keys__ == {"metadata"} - async def exercise(): - store = KuzuStore(str(tmp_path / "codegen.kuzu")) - async with SelfGraph(store, schema=schema, schema_mode="off") as graph: - with pytest.raises(ValidationError, match="missing required property 'age'") as rejected: - await person.create(graph, "Rejected", {}) - assert rejected.value.code == "schema_violation" - assert await graph.entities.get("person:rejected") is None - ada = await person.create(graph, "Ada", {"age": 42}) - bea = await graph.entities.create("Bea", "Person", properties={"age": 37.0}) - assert (await person.get(graph, ada.id)).properties == {"age": 42} - assert type((await person.get(graph, bea.id)).properties["age"]) is int - assert await person.get(graph, "person:missing") is None - parent = await graph.entities.create("Parent", "Being", properties={"age": 70}) - assert await person.get(graph, parent.id) is None - legacy = await graph.entities.create("Legacy", "Person") - with pytest.raises(ValidationError, match="missing required property 'age'"): - await person.get(graph, legacy.id) - with pytest.raises(ValidationError, match="should be datetime"): - await knows.create(graph, ada.id, bea.id, {"since-date": "invalid"}) - edge = await knows.create(graph, ada.id, bea.id, {"since-date": "2024-05-01"}) - assert (await knows.get(graph, edge.id)).properties == {"since-date": "2024-05-01"} - - asyncio.run(exercise()) + async def exercise(graph): + with pytest.raises(ValidationError, match="missing required property 'age'") as rejected: + await person.create(graph, "Rejected", {}) + assert rejected.value.code == "schema_violation" + assert await graph.entities.get("person:rejected") is None + ada = await person.create(graph, "Ada", {"age": 42}) + bea = await graph.entities.create("Bea", "Person", properties={"age": 37.0}) + assert (await person.get(graph, ada.id)).properties == {"age": 42} + assert type((await person.get(graph, bea.id)).properties["age"]) is int + assert await person.get(graph, "person:missing") is None + parent = await graph.entities.create("Parent", "Being", properties={"age": 70}) + assert await person.get(graph, parent.id) is None + legacy = await graph.entities.create("Legacy", "Person") + with pytest.raises(ValidationError, match="missing required property 'age'"): + await person.get(graph, legacy.id) + with pytest.raises(ValidationError, match="should be datetime"): + await knows.create(graph, ada.id, bea.id, {"since-date": "invalid"}) + edge = await knows.create(graph, ada.id, bea.id, {"since-date": "2024-05-01"}) + assert (await knows.get(graph, edge.id)).properties == {"since-date": "2024-05-01"} + + run(exercise(fresh_graph("codegen", schema=schema, schema_mode="off"))) GOLDEN = """from dataclasses import dataclass