Skip to Content
CLI

CLI

The cyphra command starts a local database, validates your schema, generates the typed client and runs migrations. Install it as a dev dependency:

pnpm add -D @cyphra/cli

App code depends on cyphra separately (see Getting started). The CLI loads ./.env automatically.

CommandDescription
cyphra initScaffold cyphra.json, schema.cyphra, migrations/, .env.example (existing files are kept)
cyphra devRun a local Neo4j 5 in Docker for this project and write .env (--stop, --reset, --port, --http-port, --image, --watch)
cyphra generateGenerate the typed client (cyphra.gen.ts) and, if configured, zod schemas (--watch, --zod, --zod-coerce, --zod-omit-generated)
cyphra migrate devGenerate a migration from schema changes, then apply pending ones (--name, --create-only)
cyphra migrate diffPrint the migration migrate dev would generate
cyphra migrate deployApply pending migrations
cyphra migrate statusApplied / pending / modified migrations, uncaptured changes and drift (--json, --schema; exit 1)
cyphra migrate resetEmpty a local database, reapply every migration, then run the seed (--yes, --force, --skip-seed)
cyphra db seedRun the seed command from cyphra.json
cyphra studioBrowse and edit the data in a local web UI built from the schema (details; --port, --host, --no-open, --read-only)
cyphra migration:create <name>Empty .mjs migration to write by hand
cyphra pullIntrospect the database and write schema.cyphra (--print, --force, --interface <labels…>)
cyphra import graphql <files>Convert @neo4j/graphql v7 type definitions to schema.cyphra (--out, --merge, --force, --print, --url, --id-fields, --add-interface-labels)
cyphra graphql check <files>Report what compat.v7.makeSchema does not serve in v7 type definitions (details; --json; exit 1)
cyphra graphql printPrint the native GraphQL API’s SDL (details; --config, --export, --out, --check)
cyphra graphql migrate-operations <files>Rewrite v7 operations into native ones, report what cannot be translated (details; --dry-run, --check, --json)
cyphra graphql compare <files>Run v7 operations and their translations on both APIs, report differences (details; exit 1)
cyphra graphql migrate-rules <files>Draft native rules from @authorization / @authentication (details; --out, --json)
cyphra import prisma <schema>Convert a Prisma schema to schema.cyphra, foreign keys to edges (details; --out, --merge, --force, --print)
cyphra import neogma <files>Convert neogma models (decorator classes or ModelFactory) to schema.cyphra (details; --out, --merge, --force, --print)
cyphra pushApply constraints and range, vector and full-text indexes directly (prototyping)
cyphra validateParse and validate the schema; warnings (nearly identical relationship types) go to stderr
cyphra formatFormat the schema in place, keeping comments (--check exits with 1 instead of writing; --codemod also rewrites @relationship(…) fields into @out / @in)
cyphra schema printCanonical pretty-print of the schema
cyphra schema ddlPrint the constraint and index DDL (no database)

cyphra.json

{ "schema": "./schema.cyphra", "migrations": "./migrations", "generate": "./cyphra.gen.ts", "runtimeImport": "cyphra", "dialect": "neo4j", "seed": "tsx seed.ts", "generators": { "zod": { "output": "./src/cyphra.zod.ts", "coerce": true } } }

runtimeImport is the module that generated files (the client and migrations) import from. Set it to @cyphra/runtime if you depend on the scoped packages instead of cyphra. seed is optional: see cyphra db seed. generators is optional: see zod schemas. dialect is "neo4j" (default), "memgraph" or "falkordb": it decides the DDL that migrate dev, migrate diff and schema ddl write. Commands that connect use it too; when it is not set, they detect Memgraph from the server (see Memgraph). With "falkordb", they connect to FALKORDB_URL (default redis://localhost:6379) and the graph FALKORDB_GRAPH instead of the NEO4J_* variables (see FalkorDB).

Zod schemas

With generators.zod in cyphra.json, cyphra generate (and --watch, and cyphra dev --watch) also writes a module of zod  schemas, to validate API input against the schema before it reaches the client. Install zod in your project (pnpm add zod); the generated code works with zod 4 and zod 3.

OptionDefaultDescription
output"./cyphra.zod.ts"File to write, under the project root
coercefalseRead ISO 8601 strings as Dates (DateTime, Date) and decimal strings or safe integers as bigints (BigInt)
import"zod"Module to import z from ("zod/v4" to use zod 4 from zod 3.25)
omitGeneratedfalseLeave generated fields out of the create and update input schemas: an @id with a @default, and now() / cuid() / uuid() defaults

"zod": true takes every default. Without the config, cyphra generate --zod [output] writes the schemas for that run (--zod-coerce adds coercion, --zod-omit-generated sets omitGenerated); the flags also override cyphra.json.

cyphra generate --zod # cyphra.gen.ts and cyphra.zod.ts cyphra generate --zod src/db/zod.ts --zod-coerce cyphra generate --zod --zod-omit-generated # no id / createdAt in the input schemas

With omitGenerated, a public API takes UserCreateInputSchema as is, instead of UserCreateInputSchema.omit({ id: true, createdAt: true }): the client fills those fields on create, and callers cannot send them. Literal defaults (@default("member")) stay in the inputs, optional. The output schema (UserSchema) keeps every field. For a model that needs a generated field back, .extend() its input with UserSchema.shape.<field>.

For each node model User the module exports UserSchema (the properties the client returns), UserCreateInputSchema and UserUpdateInputSchema; the same three for each relationship model (its edge properties), and RoleSchema (z.enum([...])) for each enum. See Validating API input with zod for what they check.

Environment

Commands that talk to Neo4j (migrate dev | deploy | status | reset, pull, push) read NEO4J_URI, NEO4J_USERNAME (NEO4J_USER also works), NEO4J_PASSWORD and optionally NEO4J_DATABASE. The seed command inherits the same environment.

cyphra migrate status

Shows where the database stands against your migrations:

cyphra migrate status # human report cyphra migrate status --json # one JSON document on stdout cyphra migrate status --schema # compare with schema.cyphra instead of the applied migrations

It lists each migration as applied, pending, modified (the file changed after it was applied: checksum mismatch) or missing (applied, but the file is gone), counts schema changes that no migration captures yet, and reports drift: constraints and indexes that are extra, missing or defined differently in the database than the applied migrations made them. It exits with 0 when everything is in sync, 1 when anything needs attention, and 2 when the check could not run, so it can gate CI (see the GitHub Actions example). cyphra migrate dev runs the drift check before it generates a migration and warns when the database has drifted.

cyphra dev

Starts neo4j:5 in a container named after your project folder, bound to 127.0.0.1 only, with data in a named Docker volume. It waits until Neo4j accepts connections and writes .env if there is none:

cyphra dev # start (or restart) and wait until ready cyphra dev --stop # stop, keep data cyphra dev --reset # remove the container and its data cyphra dev --watch # start, then regenerate the client on schema changes (see below)

cyphra dev --reset deletes the container. To keep it and only empty the database, use cyphra migrate reset.

Watch mode

cyphra generate --watch (or -w) generates the client, then watches the schema file from cyphra.json and regenerates cyphra.gen.ts (and the zod schemas, when configured) each time you save it:

$ cyphra generate --watch [10:42:01] Wrote cyphra.gen.ts Watching schema.cyphra for changes (Ctrl+C to stop). [10:42:17] schema.cyphra: Node "Post" field "author": unknown node "Usr" (not a node model or an enum). [10:42:25] Wrote cyphra.gen.ts
  • Saves are debounced (100 ms), so one save triggers one regeneration.
  • An invalid schema prints its error and the previous cyphra.gen.ts stays in place; the watcher keeps running until the next save.
  • The schema’s directory is watched rather than the file, so editors that save by writing a temporary file and renaming it over the original (vim, JetBrains IDEs) are picked up. It uses fs.watch and works on Linux, macOS and Windows.
  • Ctrl+C stops watching and exits with 0.

cyphra dev --watch starts Neo4j first, then watches the same way. Ctrl+C stops the watcher; the container keeps running until cyphra dev --stop.

cyphra db seed

Set seed in cyphra.json to the command that loads your data. It is a shell command, run from the project root, so it can use any runtime:

{ "seed": "tsx seed.ts" }
seed.ts
import { createClient } from "./cyphra.gen.js"; const db = createClient({ uri: process.env.NEO4J_URI!, user: process.env.NEO4J_USERNAME!, password: process.env.NEO4J_PASSWORD!, }); await db.user.create({ data: { email: "ada@example.com" } }); await db.$disconnect();

cyphra db seed runs it with the CLI’s environment (including ./.env) and with node_modules/.bin on PATH, so a locally installed tsx is found. The seed’s exit code becomes the command’s exit code; without a seed entry, cyphra db seed fails with 1. cyphra migrate reset runs the seed after reapplying migrations.

cyphra studio

A local data browser built from schema.cyphra: no Neo4j Browser, no codegen. It reads cyphra.json and the NEO4J_* settings (including ./.env), starts a web server on 127.0.0.1 and opens your browser:

$ cyphra studio Cyphra Studio on http://127.0.0.1:5555/?token=Qk3… The token in the URL is required: keep it private. Stop with Ctrl+C.
Cyphra Studio: the User model as a table with typed columns, a karma ≥ 600 filter and a descending sort
  • Models. The sidebar lists node models, interfaces and relationship models with their counts. Each model opens as a table with the field types in the header, pagination, sorting by column (to-many relations sort by their count) and a filter builder whose operators follow the field type (contains and case-insensitive matches on strings, ranges on numbers and dates, has and isEmpty on lists, some / none on relations, is null everywhere).
  • Editing. Double-click a cell to edit it, or open the record to edit every field with typed inputs: a select for enums and booleans, date and time pickers, a JSON editor that validates as you type, item lists for String[] and friends, coordinates for points. Writes go through the OGM, so validation rules and unique constraints apply and their messages show next to the field.
  • Relations. Relation columns show the related node’s key or the count of related nodes; click one to open the related records, and keep following from there (a breadcrumb leads back). Edge properties of a relationship { … } model show next to the related nodes and in the relationship model’s own table, where they can be edited.
  • Linking. In a related view, Link… connects another record by its key (with the edge properties, if the relation has a relationship { … } model) and the ⊘ button of a row removes its link (the record is kept). For a relation to a union, pick the member first: a node, or an interface member, addressed by the interface’s key.
  • Delete. Before deleting, the studio lists what the onDelete rules will do: nodes deleted by a cascade, edges removed, or a Restrict relation that blocks the delete.
  • Cypher. A raw Cypher tab with JSON parameters. Queries run in a read transaction; tick Allow writes to run one in a write transaction.
  • Interfaces and unions. An interface or a union lists the nodes of every implementation or member, with their __typename (and, for a union, each row’s key); edits go to the node’s own model.

Records of a model without an @id, @unique or @@unique field can be browsed but not edited (nothing identifies one record).

Memgraph. The studio uses the "dialect" of cyphra.json, or, when it sets none, detects Memgraph from the server (as push and migrate deploy do), and shows a Memgraph badge. Fields Memgraph cannot store (Time) are read-only and left out of the filter builder; the API refuses to write them, and answers anything else Memgraph lacks (a Duration with months, a Neo4j-only procedure in the Cypher tab) with a 400 and the reason, without retrying. See the feature matrix.

OptionDescription
--port <n>Port to listen on (default 5555)
--host <h>Address to bind (default 127.0.0.1); any other address prints a warning
--no-openPrint the URL without opening a browser
--read-onlyNo edits, creates, deletes or Cypher writes: the API refuses them, the UI hides them

Security

The studio holds your database credentials, so it only answers the page it served:

  • Loopback only by default. It binds 127.0.0.1. Exposing it to the network takes an explicit --host, and prints a warning.
  • Session token. Each run creates a random token. The URL carries it once: the studio moves it to an HttpOnly, SameSite=Strict cookie and drops it from the address bar. Every API call needs that cookie and a custom header, which other sites cannot send without a CORS preflight the studio never grants (CSRF).
  • DNS rebinding. Requests whose Host is not an IP address, localhost or the --host name are refused, as are requests from another Origin.
  • No credentials in the browser. The page gets the schema and the database address without user name, password or query string. Queries run on the server.
  • Strict page. The UI is bundled in the CLI (no CDN) and served with a Content-Security-Policy that allows only its own scripts and styles, and no framing.

Treat the printed URL like a password, and prefer --read-only against shared or production databases.

cyphra pull

Reads labels, relationship types, property types, constraints and indexes from a live database and writes a .cyphra schema. It is read-only and samples up to 10,000 edges per relationship type to find their endpoints. Review the result:

  • Relation names are derived from relationship types (AUTHORED becomes authored on the start node and authoredBy on the end node), and every relation is to-many.

  • A property is required only if every node with that label had it at pull time.

  • Single-property uniqueness constraints become @id (on a property named id) or @unique; range and point indexes become @index. Composite uniqueness constraints (and node keys) become @@unique([…]), composite range indexes @@index([…]), with a name when theirs is not the default.

  • LocalDateTime, LocalTime, Time and Duration properties keep their type. A point property becomes a Point or a CartesianPoint from the CRS of up to 10,000 sampled values; a property holding both kinds is skipped with a warning.

  • Node vector indexes become Vector(N) fields with @vectorIndex(similarity: …), keeping the index name when it is not the default one (and quantization: false when it is off).

  • Node full-text indexes become @@fulltext([…]) attributes, keeping the name, analyzer and eventuallyConsistent: true when they are not the defaults. Indexes over several labels, on relationships, or on properties that were not pulled as String / String[] fields are skipped with a warning.

  • Nodes with several labels are read as one model each, plus interfaces and dynamic labels. In each group of labels seen together, pull picks one label per node as its model, so that every label combination holds exactly one model label. Each other label is then:

    • an interface when it is on every node of the models it is seen with (never alone). It gets the properties all its nodes share (and those its constraints cover), and each model implements it with the rest. A node can implement several unrelated interfaces: [Employee, Person, Archivable], [Customer, Person] and [Doc, Archivable] give node Employee implements Archivable, Person. Interfaces whose nodes all carry another one extend it: with [Employee, Staff, Person], [Contractor, Staff, Person] and [Customer, Person], pull writes interface Staff extends Person, node Employee implements Staff, node Contractor implements Staff and node Customer implements Person. A property two unrelated interfaces of a node could both hold stays on the nodes, unless only one of the interfaces constrains or indexes it.
    • a dynamic label (@@labels([Archived])) when it is on some nodes of the model only, its nodes have no property the model’s other nodes never have, it has no constraint or index, and some nodes of the model carry none of the model’s dynamic labels. With [Post], [Post, Archived] and [User, Archived], both Post and User get @@labels([Archived]). When every :Post is also :Draft or :Published, those are the models and Post their interface.

    A layout that fits none of this stays one model per label, with a warning. So does one that fits in several ways: nodes always labelled [Employee, Person] (a shared label with a single implementation) could be either way round. Tell pull which labels are interfaces there: cyphra pull --interface Person (repeat the label, or give a comma-separated list, for several).

  • Unions are never inferred (a union adds no label): edges of one type from a label to several others become one relation per target (tagsPost Post[], tagsUser User[]). Declare the union and its relation field by hand if that is the model.

  • Unsupported or mixed types (e.g. a property that is a string on some nodes and an integer on others) and names that are not identifiers are skipped with a warning.

  • Integers are pulled as Int and strings as String: the database cannot tell a BigInt, an enum or a Json field apart from those. Change the types by hand where it applies (for example an Int whose values exceed 2^53 to BigInt, a status string to an enum).

The native GraphQL API (experimental) is generated from schema.cyphra and its config (graphql.config.ts). cyphra graphql print prints its SDL, sorted, without a database: the contract to commit and review.

cyphra graphql print # to stdout cyphra graphql print --out schema.graphql # write it cyphra graphql print --check # CI: compare with the committed schema.graphql
  • The config is graphql.config.ts (or .mts, .js, .mjs) in the project root, or the file given with --config. Its default export is used, else its only export, else the one named with --export. Without a config file, the defaults apply (every read operation). TypeScript configs (and --typedefs modules) are transpiled with typescript on import, with no extra flag, and their relative NodeNext imports (./rules.js for rules.ts, .mjs for .mts) resolve to the TypeScript files.
  • --check exits with 1 when the generated SDL differs from the file (--out, default schema.graphql), and lists the changes graphql’s findBreakingChanges / findDangerousChanges report (a field removed by a schema edit or a toggle, a type changed, …), so they show up in review.

Migrate operations to the native API

cyphra graphql migrate-operations rewrites the operations a frontend sends to compat.v7 into operations of the native API, following the mapping table. It reads .graphql / .gql files and the templates of TS and JS files tagged gql or graphql (or after a /* GraphQL */ comment), and changes nothing else: rebuild your generated client types with your own codegen afterwards.

cyphra graphql migrate-operations "src/**/*.{graphql,ts,tsx}" --typedefs typeDefs.graphql --dry-run cyphra graphql migrate-operations "src/**/*.{graphql,ts,tsx}" --typedefs typeDefs.graphql cyphra graphql migrate-operations "src/**/*.{graphql,ts,tsx}" --typedefs typeDefs.graphql --check # CI
src/movies.graphql:2:1 translated Movies src/cast.ts:14:20 NOT TRANSLATED Cast src/cast.ts:16:43 cannot translate: movies(where).actorsConnection.some.edge: the native API has no filters on edge properties (filter on the related node, or use a Cypher-backed field) src/pages.ts:9:31 translated Page src/pages.ts:9:31 note: page.edges.cursor: dropped: the native API has cursors per page (pageInfo), not per node 3 documents in 3 files: 2 translated (1 with notes), 1 not translated. 2 files rewritten.
  • Each document (a file, or a template) is translated as a whole, or not at all: one construct with no native equivalent (an edge filter, a connect by a non-unique where, a variable holding a v7 input such as $where: MovieWhere, a ${…} substitution in the template) leaves the document as it is, with a # cyphra: not translated: … comment above the operation. A selected field the native API does not have (a @cypher field not declared in cypherFields) is dropped with a # cyphra: … note. Run it again after fixing: the comments are replaced, not repeated, and native documents are left alone. A document that only uses fields both APIs serve alike (custom root fields and types, served by extend) is left byte-identical and reported as unchanged; so is such an operation inside a translated document.
  • The schemas: --typedefs names the v7 type definitions (.graphql files, or a module exporting typeDefs); the native one is schema.cyphra given with --schema, else the conversion of cyphra import graphql (--id-fields, --add-interface-labels as for the import). The native config is graphql.config.ts (or --config, --export, as for graphql print); without one, every operation of every model is assumed on. A mutation the config does not serve is reported.
  • --tag doc also reads the templates passed to doc(…) (or doc<T>(…)); repeat it or separate names with commas. --no-comments writes no # cyphra: comment.
  • --dry-run prints the translated documents and writes nothing. --check writes nothing and exits with 1 while a v7 operation is left (translatable or not). --json prints every document with its status (translated, blocked, native, unchanged, invalid, skipped) and issues.

Compare compat.v7 and the native API

cyphra graphql compare is the dual-run check: it runs each v7 operation on compat.v7 and its translation (the codemod’s, in memory) on the native API, maps the v7 result to the native shape and reports the differences, operation by operation.

# In-process: both APIs on the database of NEO4J_URI (reads only) cyphra graphql compare "operations/*.graphql" --typedefs typeDefs.graphql # On a local, disposable database: reset and seed before each run, mutations included cyphra graphql compare "operations/*.graphql" --typedefs typeDefs.graphql --reset --seed seed.cypher --yes # Against two running endpoints cyphra graphql compare "operations/*.graphql" --typedefs typeDefs.graphql \ --v7-url http://localhost:3000/api/graphql --native-url http://localhost:3000/api/graphql/v2 \ --header "Authorization: Bearer $TOKEN"
operations/01-movies.graphql:1:1 same Movies operations/02-page.graphql:1:1 same (known differences) Page movieFindMany.pageInfo.endCursor: v7 (not comparable), native "WzEsIm0tMSJd" (known: v7 cursors are offsets, native cursors are keysets) operations/03-cast.graphql:1:1 DIFFERS Cast movieFindMany.nodes[0].actors: v7 [{"name":"Ed"}], native [{"name":"Ed"},{"name":"Ed"}] operations/04-roles.graphql:1:1 not translated Roles: movies(where).actorsConnection.some.edge: … 4 operations: 2 same (1 with known differences), 1 differ, 1 not translated, 0 skipped.
  • Errors are compared by their number, then paired, on their message, extensions.code (UNAUTHENTICATED against FORBIDDEN is a difference) and path (the v7 path mapped to the native shape: movies is movieFindMany). A v7 error on a non-null root field nulls the whole data where the native root field is null on its own: a known difference.
  • Lists are compared as multisets (--ordered compares them in order). Differences the native API has on purpose are reported as known, not as failures: cursors, connect as a MERGE, a unique update failing with NOT_FOUND where v7 returned an empty list. The command exits with 1 when another difference is found.
  • In-process, the v7 API is compat.v7.makeSchema({ typeDefs }) and the native one native.makeSchema on schema.cyphra (or the conversion) and the config, on the database of NEO4J_URI / NEO4J_USERNAME / NEO4J_PASSWORD. Without --reset, mutations are skipped and reads run on the current data; --reset deletes every node before each run and applies --seed, so use a disposable database. It runs the safety check of cyphra migrate reset: a URI that does not look local (local: no +s / +ssc scheme, and localhost, a loopback address, 0.0.0.0, host.docker.internal or a single-label container name) is refused unless --force, and the command asks before the first reset unless --yes (-y) or --force; without a terminal it refuses instead of asking. Over HTTP, mutations are skipped unless --allow-mutations (they then run once per API, on the same data).
  • Next to NN-name.graphql, NN-name.variables.json holds the variables and NN-name.jwt.json a decoded JWT payload (passed as jwt to both APIs, in-process); --jwt gives one to every operation. Custom resolvers are not loaded in-process: compare operations on custom fields over HTTP.

Draft native rules from @authorization

cyphra graphql migrate-rules drafts the native rules and authenticated of a defineGraphQL config from the @authorization and @authentication directives of the v7 type definitions. The output is TypeScript to review and merge into graphql.config.ts: it is never applied, because the native rules apply differently on purpose.

cyphra graphql migrate-rules typeDefs.graphql --out graphql.rules.ts --type-map ./cyphra.gen.js
graphql.rules.ts
export default defineGraphQL<CyphraTypeMap, Ctx>({ models: { Post: { // TODO(cyphra): v7 field filter on Post.notes: {node: {author: {id: {eq: "$jwt.sub"}}}} (READ) // TODO(cyphra): not drafted: v7 field rules filter the node (or fail the request) when the field is selected or written; … rules: { // v7 filter #1 (READ, requireAuthentication: false): {node: {published: {eq: true}}} // v7 filter #2 (READ, UPDATE, DELETE): {node: {author: {id: {eq: "$jwt.sub"}}}} read: ({ ctx }) => anyOf({ published: { equals: true } }, allOf(authenticated(ctx), { AND: [given(ctx.jwt?.sub, (v0) => ({ author: { is: { id: { equals: v0 } } } }))] })), …
  • filter rules become read / update / delete rules (several rules of one directive with anyOf, like v7’s OR), validate rules on CREATE the create rule (context-only) or after.create, on UPDATE / DELETE / READ a rule that leaves the node out (v7 failed the request with Forbidden), CREATE_RELATIONSHIP / DELETE_RELATIONSHIP connect / disconnect rules, @authentication authenticated. "$jwt.sub" becomes ctx.jwt?.sub (at the @jwtClaim path), "$context.x" ctx.x, requireAuthentication authenticated(ctx).
  • A comparison with a missing $jwt / $context value matches nothing, as in v7 (given).
  • What the native API cannot express, or only in a way that could grant more access, is a TODO(cyphra) comment with the v7 rule: field-level rules, @authentication(jwt), filters the native where does not have (edge properties, aggregations), relationship rules that depend on the node from its own side. The summary counts the v7 rules drafted, partly drafted and TODO; --json prints { code, entries, drafted, partial, todo }.
  • --type-map types the draft against the generated client (CyphraTypeMap); without it, the draft uses the loose TypeMap of cyphra.

Check @neo4j/graphql type definitions

Before serving @neo4j/graphql v7 type definitions with compat.v7.makeSchema, list in one run everything it does not serve yet (or that v7 rejects too). No database is needed:

cyphra graphql check typeDefs.graphql cyphra graphql check src/**/*.graphql --json

The files are checked together, like the type definitions of one makeSchema call. Each issue has its file, line and column, a code (UNSUPPORTED: not served by @cyphra/graphql yet, INVALID: rejected by v7 as well, with v7’s message, SYNTAX: the file does not parse) and the message makeSchema throws:

user.graphql:2:11 UNSUPPORTED User.id: @unique is not supported by @cyphra/graphql yet. user.graphql:3:3 INVALID User.best: Non-list relationship property "best" cannot have non-nullable type. post.graphql:3:17 UNSUPPORTED Post.title: @coalesce is not supported by @cyphra/graphql yet. 3 issues in 2 files (2 unsupported by @cyphra/graphql, 1 invalid for @neo4j/graphql 7).

The command exits with 1 when there are issues, so it can run in CI. --json prints { "files": [...], "issues": [{ "code", "message", "location": { "type", "field", "source", "line", "column" } }] }. The same check is available in code as compat.v7.checkTypeDefs (GraphQL).

Import from @neo4j/graphql

If your app runs on @neo4j/graphql v7, convert its type definitions to a Cyphra schema in one step:

cyphra import graphql typeDefs.graphql # writes the schema from cyphra.json cyphra import graphql src/**/*.graphql --merge # add to an existing schema.cyphra

Pass one or more .graphql files. The schema goes to the schema path in cyphra.json (or ./schema.cyphra), or to --out <path>. An existing file is never overwritten unless you pass --force. With --merge, your models, fields and comments stay as they are: missing fields and new models are added, and when a field exists on both sides your version wins.

What converts:

  • @node types become node models. A custom label in @node(labels) becomes the model name, since a Cyphra model’s name is its label.
  • ID, String, Int, Float, BigInt, Boolean, DateTime, Date, LocalDateTime, LocalTime, Time, Duration, Point and CartesianPoint (the same Neo4j types), lists, and required or optional from nullability. Enums become Cyphra enums with the same values (only the ones a converted field uses).
  • @id becomes @id @default(uuid()), @timestamp (on DateTime and Time) becomes @default(now()), @default keeps its value, and @unique (from v6 and earlier) stays @unique.
  • @relationship(type, direction) becomes a relation field (@out(TYPE) / @in(TYPE)), and a @relationshipProperties type becomes a relationship model.
  • A union of @node types (union Search = Movie | Genre) becomes a Cyphra union with the same members, and @relationship fields to it become relation fields to the union. Neither adds a label, so the data stays as it is; the root searches query becomes db.search.findMany. Properties on a relationship to a union become one relationship model with the union at that end (relationship Watched { from User to Media }, see unions), which the members’ inverse fields with the same properties type share. A union of types without @node (@cypher result types) is reported.
  • @fulltext(indexes: [{ indexName, queryName, fields }]) becomes one @@fulltext([fields], name: indexName) per index, so cyphra migrate creates the indexes. queryName names a GraphQL query field and is listed as ignored.
  • Shared labels and interfaces, see below.
  • id: ID! fields backed by a uniqueness constraint, with --url or --id-fields, see below.

Shared labels and interfaces

v7 writes every label of @node(labels) on create and matches on all of them, so @node(labels: ["Lab", "LearningActivity"]) stores (:Lab:LearningActivity). That is what a Cyphra interface is, so a label after the first becomes one:

type Lab @node(labels: ["Lab", "LearningActivity"]) { id: ID! @id title: String! environment: String! } type Quiz @node(labels: ["Quiz", "LearningActivity"]) { id: ID! @id title: String! passMark: Int! }
interface LearningActivity { id String @id @default(uuid()) title String } node Lab implements LearningActivity { environment String } node Quiz implements LearningActivity { passMark Int }
  • Common fields move to the interface when every type carrying the label declares them the same way (type, nullability, directives). A @unique or @id that moves then covers every :LearningActivity node (one constraint on the shared label), and the report says so. A label on one type becomes an interface without fields.
  • An id that only some types mark @id (id: ID! @id on Lab, a plain id: ID! on Quiz) still lines up: the interface declares id String @id, with @default(uuid()) when one of the types generated its ids. The Quiz ids must then be unique across :LearningActivity nodes, and are generated too when you create one without an id (an inherited field has a single declaration); the report says so.
  • A field that differs only in its @default (kind: String! @default(value: "lab") on Lab, @default(value: "quiz") on Quiz) does not prevent the interface: it stays on each type, with its own default, and the report lists the defaults.
  • When the fields do not line up (a common field declared String! on one type and Int on another), the label becomes @@labels([LearningActivity]) on each type instead. Cyphra reads and filters on it, but does not add it on create: pass $labels: { add: ["LearningActivity"] } when you create.
  • A label that is another type’s label (@node(labels: ["Mentor", "Learner"]) next to a Learner type) cannot be expressed and is reported.

A GraphQL interface adds no label in v7: a Movie implementing Production is stored as (:Movie). It becomes a Cyphra interface (relationships to it and @relationshipProperties on them included: relationship ActedIn { from Person to Production }) when its implementations carry its name as a label, @node(labels: ["Movie", "Production"]), and declare its fields the same way. When they do not carry the label, the interface is reported and its relationships are not converted, so the schema keeps matching the stored nodes. Pass --add-interface-labels to map it anyway: the report then gives the Cypher that adds the label to the existing nodes (MATCH (n:Movie) SET n:Production), to run before reading them through Cyphra.

Unique fields and @id

The type definitions do not say whether id: ID! is unique: v7 @id generates a UUID but creates no constraint, and a plain ID! field is just a string. Without more information, the import keeps id: ID! as id String. Give it the database, or name the fields:

cyphra import graphql typeDefs.graphql --url # NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD cyphra import graphql typeDefs.graphql --url bolt://neo4j:secret@localhost:7687 cyphra import graphql typeDefs.graphql --id-fields User.id,Tag.key
  • --url reads the database’s constraints (read-only, SHOW CONSTRAINTS; without a value, the connection of the environment and the dialect of cyphra.json, like cyphra pull). A uniqueness constraint or node key on one property marks the field: an ID field becomes the node’s @id, another field (or a second ID field, or an optional one) @unique. A constraint on a shared label marks the interface’s field. A constraint over several properties becomes @@unique([…]). The report lists every field it marked, and every ID field no constraint covers.
  • --id-fields Type.field (comma-separated or repeated) marks fields @id without a database. Type is a @node type, a shared label or an interface, field the GraphQL field name.
  • Neither adds a default: the application gives the values, as it did with v7. A field already marked @id in the type definitions keeps @id @default(uuid()).
  • A field whose constraint is on each type’s own label (:Lab(id)) stays on each type rather than moving to the shared interface, so the constraint keeps its label.

Everything else is listed in a report, never dropped silently. Fields that were not converted also appear as comments in the schema. The command exits with 0 when it wrote the schema, warnings included, and with 1 only when the type definitions are not valid GraphQL (or --url cannot read the database):

Wrote schema.cyphra (2 node(s), 1 relationship model(s)) Not converted (1): Movie.similar @cypher: @cypher fields are computed by a Cypher query: not converted (compat.v7 still serves it); with the typed client, write it as a query Converted with differences (4): Movie.id @id: became @id @default(uuid()); Cyphra also adds a uniqueness constraint, which v7 @id does not Person.id @id: became @id @default(uuid()); Cyphra also adds a uniqueness constraint, which v7 @id does not Person.name @unique: @unique was removed in @neo4j/graphql v7; Cyphra keeps it and creates the uniqueness constraint Actor @node(labels): label of Person: mapped to interface Actor (Cyphra writes and matches the label, like v7); it declares no field

Not converted today: custom scalars, interfaces whose implementations do not carry their label (unless you pass --add-interface-labels, see above), @cypher and @customResolver fields, @authentication and @authorization rules, @vector indexes (the type definitions carry neither the dimensions nor the similarity: declare a Vector(N) field with @vectorIndex by hand), and update timestamps. API-only settings such as @plural, @selectable or @filterable are listed as ignored. Run cyphra validate after the import, then cyphra migrate dev.

Import from Prisma

Moving from Prisma and PostgreSQL (or MySQL, SQLite, MongoDB) to Neo4j? Convert schema.prisma to a Cyphra schema, with foreign keys turned into edges:

cyphra import prisma prisma/schema.prisma # writes the schema from cyphra.json cyphra import prisma prisma/schema # a multi-file schema folder cyphra import prisma prisma/schema.prisma --print # to stdout, report on stderr

The options are the ones of cyphra import graphql: --out <path>, --force to overwrite, --merge to add to an existing schema without touching what is there, and --print. Prisma itself is not needed: the importer reads the file. The migration guide covers the rest of the move (data and queries).

Models, fields and attributes

PrismaCyphra
model, enumnode, enum (same names, same values)
String, Int, BigInt, Float, Boolean, DateTime, Jsonthe same types
DecimalFloat, reported: about 15 significant digits
?, [] (scalar lists)?, []; Json[] becomes one Json holding the array
@id, @unique, @@unique([a, b]), @@index([a, b])the same; one-field @@unique / @@index become @unique / @index
@@id([a, b])@@unique([a, b]), reported (a Cyphra @id is one field)
@@fulltext([a, b])@@fulltext([a, b])
@default(cuid()), uuid(), now(), a literalthe same
@default(uuid(7)), ulid(), nanoid(), auto()uuid() or cuid(), reported
@default(dbgenerated("gen_random_uuid()"))@default(uuid()), reported (other SQL is not converted)
@updatedAt@default(now()), reported: set it yourself on update
@db.VarChar(n), @db.Char(n)@length(max: n), checked by the client
DateTime @db.Date, @db.Time, @db.TimetzDate, LocalTime, Time

Relations

  • A foreign key (author User @relation(fields: [authorId], references: [id]) with authorId String) becomes an edge from the referenced model to the model holding the key, (User)-[:HAS_POSTS]->(Post): User.posts is OUT, Post.author is IN. The key scalar (authorId) is dropped, since the edge is the link, and left as a comment in the model. One-to-one and one-to-many work the same way.
  • An implicit many-to-many (tags Tag[] on Post, posts Post[] on Tag) becomes one edge type, from the model whose name sorts first (Prisma’s A side): (Post)-[:HAS_TAGS]->(Tag).
  • An explicit join model becomes a relationship model when it has exactly two required relations, a @@id or @@unique over their keys, and nothing else pointing to it. Its other fields become edge properties: OrderItem { order, product, quantity } becomes relationship OrderItem, ORDER_ITEM edges from Order to Product with a quantity property, and Order.items lists products, each with its $edge. The row’s own id, if any, is dropped.
  • Edge type names. @relation("WrittenPosts") gives WRITTEN_POSTS (upper snake case). A join model gives its name (ORDER_ITEM). Otherwise, HAS_ and the field on the edge’s start model: User.posts gives HAS_POSTS, Post.tags gives HAS_TAGS. A name already used between the same two models gets a _2 suffix. Rename them before your first migration if you prefer verbs (AUTHORED): the type is only in schema.cyphra.
  • onDelete moves to the referenced model’s field, where a Cyphra rule lives: Post.author … onDelete: Cascade becomes onDelete: Cascade on User.posts. Restrict stays Restrict, NoAction becomes Restrict, SetNull is Cyphra’s default and SetDefault is reported. Without onDelete, Prisma’s default applies: Restrict for a required key, SetNull for an optional one. On a join model, Cascade needs no rule, since deleting a node removes its edges. onUpdate has no equivalent (edges hold no key values) and is listed as ignored.
  • @@index on foreign keys is dropped (Neo4j follows the edge), and a key is removed from a composite @@index. A @@unique that covers a foreign key cannot be converted: Neo4j constraints do not span relationships.

Not converted, and reported: Bytes, Unsupported(…), autoincrement() and sequence() (the id stays an Int without a default: keep the existing ids when you move the data), other dbgenerated(…) defaults, fixed dates as defaults, views, and @ignore / @@ignore fields and models. @map and @@map are reported because Cyphra uses the field and model names as property names and labels. Composite types (MongoDB) become Json fields. datasource, generator and native types without an effect (@db.Uuid, @db.Text) are listed as ignored.

The report has the same three sections as the GraphQL one:

Wrote schema.cyphra (5 node(s), 1 relationship model(s)) Not converted (2): Category.id @default(autoincrement()): Neo4j has no sequences: not converted; keep the existing ids when you migrate the data, and set new ones yourself (or switch to String @id @default(cuid())) Product.image Bytes: Neo4j has no byte arrays in Cyphra: not converted; store the bytes elsewhere (object storage) or as base64 text in a String Converted with differences (13): OrderItem join model: became relationship OrderItem: (Order)-[:ORDER_ITEM]->(Product) edges with its other fields as properties; Order.items and Product.orderItems now list Product and Order nodes (the properties are on $edge) Product.price Decimal: became Float: a 64-bit float keeps about 15 significant digits, so exact decimals (money) can round; use a String or an Int of cents to keep them exact Product.categoryId foreign key: dropped: the HAS_PRODUCTS edge of category replaces the key (Neo4j links nodes with edges, not key columns) …

Run cyphra validate after the import, then cyphra migrate dev for the constraints and indexes.

Import from neogma

Moving from neogma to Cyphra? Convert its models to a Cyphra schema:

cyphra import neogma src/models # every model file under a folder cyphra import neogma src/models/user.ts src/models/order.ts --print

Pass model files (.ts, .js, .mts, .cjs, …) or folders. In a folder, files that do not mention neogma or TypeBox, tests, .d.ts files and node_modules are skipped. The options are the ones of cyphra import graphql: --out <path>, --force, --merge and --print.

The importer reads the files with the TypeScript compiler and never runs them: no connection to Neo4j, no import of your app. It follows constants (const email = Type.String({ … }), a defineRelationshipProperties({ … }) object, a static class field) within the files you pass, so pass the files that hold the shared schemas too.

What it reads (checked against neogma 2.0.5, November 2026):

  • neogma 2 decorator classes: @Node({ label }), @PrimaryKey(schema), @Property(schema) and @Relationship({ name, direction, model, properties }), from neogma (TC39 decorators) or neogma/legacy (experimental decorators). Without a label, the class name is the label, as in neogma.
  • ModelFactory({ label, schema, primaryKeyField, relationships, statics, methods }, neogma), the neogma 1 API that neogma 2 still accepts, with revalidator schemas ({ type: 'string', required: true }) or TypeBox ones, plus Model.addRelationships({ … }) and hooks or methods assigned to the model afterwards.

Models and properties

neogmaCyphra
label: 'User'node User (a Cyphra model’s name is its label)
label: ['User', 'Account']node User implements Account, with an empty interface Account
@PrimaryKey(…), primaryKeyField@id; format: 'uuid' also gets @default(uuid()), reported
Type.String(), Type.Boolean(), Type.BigInt()String, Boolean, BigInt
Type.Number()Float
Type.Integer(), type: 'integer'Int, reported: the driver stored the JS numbers as FLOAT
Type.String({ format: 'date-time' }), format: 'date'DateTime, Date, reported: stored as strings until you convert
Type.Array(T)T[]
Type.Optional(T), Type.Union([T, Type.Null()])T? (an optional list becomes a list, reported)
revalidator without required: trueT? (revalidator properties are optional by default)
Type.Union([Type.Literal('a'), …]), Type.Enum([…]), enuman enum (values that are not identifiers: a String + @regex)
Type.Object(…), Type.Record(…), type: 'object'Json, reported
no schema (@Property(), Type.Any())the type of the field’s annotation (string, number[], …)
minLength / maxLength, allowEmpty: false@length(min, max)
minimum / maximum (exclusive… on integers)@min / @max
format: 'email', 'url' / 'uri', 'uuid'@email, @url, @regex (UUID)
pattern (a string or a /…/i literal)@regex(pattern, flags)
minItems / maxItems@size(min, max)
default@default(…), reported: neogma validates but never fills defaults

Relationships

  • Each alias becomes a list field: Orders: { name: 'PLACED', direction: 'out', model: Orders } gives Orders Order[] @out(PLACED). Field names are the aliases, unchanged. 'self' points to the same node.
  • neogma declares each side on its own model. When both sides are declared (direction: 'out' on one, 'in' on the other, same name), they become two fields over the same edges, which Cyphra reads as inverses of each other. A side declared only once stays one field; add the other side to the schema if you want it.
  • direction: 'none' becomes OUT, reported: a Cyphra field follows one direction.
  • Relationship properties (object, array or function form, on either side or both) become one relationship model per type and pair of nodes, named after the type (RATED gives Rated). Cyphra uses the stored property name (rating), not the neogma alias (Rating), and the report says so.

Not converted, and reported: hooks (beforeCreate, beforeDelete; port them to query hooks), statics and instance methods (port them to client extensions), custom validators (Type.Refine, revalidator conform), unions of different types, formats other than the ones above, multipleOf, uniqueItems, rules on list elements, and anything the importer cannot read statically (a schema built by a function, a label from a variable defined elsewhere). Custom error messages are listed as ignored.

neogma creates no constraints, while @id does: before the first cyphra migrate dev, check that the existing primary keys have no duplicates. The report has the same sections as the other importers:

Wrote schema.cyphra (3 node(s), 1 relationship model(s)) Not converted (6): Customer beforeCreate: hook: not converted; port it to a query hook: db.$extends({ query: { customer: { create, createMany } } }) Customer static findByEmail: static method: not converted; add it as a model method: db.$extends({ model: { customer: { findByEmail } } }) Product.price Type.Refine: custom validator: not converted; check the value in a query hook (db.$extends({ query })) … Converted with differences (13): Customer.id format: "uuid": neogma does not generate keys: Cyphra now sets a uuid() when create gets no id (you can still pass one) Customer.createdAt format: "date-time": a date-time string became a DateTime (a Neo4j DATETIME): convert the stored strings with datetime() when you move the data Contains.quantity alias: the alias Quantity (on Order.Products) is not kept: Cyphra uses the stored name, $edge: { quantity } …

Run cyphra validate after the import, then cyphra migrate dev for the constraints and indexes.

Last updated on