Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)). |
Expand Down
42 changes: 42 additions & 0 deletions docs/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 dictionary with the same shape, to the graph or to one
Expand Down
11 changes: 10 additions & 1 deletion src/selfgraph/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
sync_glob,
)
from .schema import ContradictionMode, Schema, SchemaMode
from .schema_codegen import generate_schema_types
from .stores._cypher import parse_auth
from .tiers import LADDERS, LEVELS

Expand Down Expand Up @@ -101,6 +102,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"""
Expand Down Expand Up @@ -424,6 +426,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"))

Expand Down Expand Up @@ -883,6 +889,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)
Expand Down Expand Up @@ -1704,7 +1713,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:
Expand Down
160 changes: 160 additions & 0 deletions src/selfgraph/schema_codegen.py
Original file line number Diff line number Diff line change
@@ -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"
Loading
Loading