{"data":{"slug":"github-google-skills-skills-cloud-spanner-relational-to-graph-d6b7559fda41","title":"Spanner Relational Schema to Graph Conversion","summary":"Converts existing Spanner relational schemas into property graphs for graph-based analysis without modifying relational tables. Generates `CREATE PROPERTY GRAPH` DDL statements for node and edge tables.","url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-spanner-relational-to-graph-d6b7559fda41","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-google-skills-skills-cloud-spanner-relational-to-graph-d6b7559fda41","markdown_url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-spanner-relational-to-graph-d6b7559fda41.md","download_url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-spanner-relational-to-graph-d6b7559fda41\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Before executing any `gcloud`, REST API, or MCP command, you must read and follow the instructions in [Usage Attribution](references\/attribution.md). Ensure the Google Cloud SDK is installed, an active Google Cloud project with billing is configured, and appropriate IAM roles are assigned.","instructions":"---\nname: spanner-relational-to-graph\nmetadata:\n  version: \"1.0.0\"\n  category: Databases\ndescription: >-\n  Analyzes existing Spanner relational schemas on Google Cloud (DDL, foreign\n  keys, interleaved tables, and junction tables) and generates\n  `CREATE PROPERTY GRAPH` DDL statements (`NODE TABLES`, `EDGE TABLES`) without\n  modifying underlying relational tables. Use when mapping existing Spanner\n  tables to a Spanner Graph, identifying node and edge candidates from\n  relational tables, creating SQL bridge views for implicit `ARRAY`\/`JSON` or\n  type-mismatched relationships, mapping polymorphic or self-referential tables,\n  or troubleshooting `CREATE PROPERTY GRAPH` DDL compiler errors. Don't use for\n  greenfield physical table design (use spanner-graph-schema-best-practices) or\n  tuning slow ISO GQL queries (use spanner-graph-query-tuning).\n---\n\n# Spanner Relational-to-Property-Graph Schema Conversion\n\nConvert an existing Spanner relational schema into a valid, production-ready\n`CREATE OR REPLACE PROPERTY GRAPH` DDL definition while keeping existing\nrelational tables intact.\n\n## Usage Attribution\n\n**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you MUST\nread and follow the instructions in\n[Usage Attribution](references\/attribution.md).\n\n## Prerequisites & Cloud Environment Setup\n\nWhen inspecting a live Spanner instance or verifying DDL (see `spanner-basics`\nfor general Spanner instance provisioning and MCP setup):\n\n1. **Google Cloud SDK (`gcloud`)**: Ensure the CLI is installed (see\n   [Install the Google Cloud SDK](https:\/\/docs.cloud.google.com\/sdk\/docs\/install-sdk.md.txt)).\n2. **Project, Billing & API**: Verify an active Google Cloud project with\n   billing enabled (required even when provisioning a free trial instance) is\n   configured (`gcloud config set project {project_id}`) and, after the user\n   confirms, enable the Spanner API\n   (`gcloud services enable spanner.googleapis.com`). Ask the user before\n   changing the active project, billing, or enabled APIs, or creating or\n   deleting instances, because these commands change the user's Google Cloud\n   environment and can incur costs.\n3. **Authentication & IAM Roles**: Authenticate via `gcloud auth login` or\n   `gcloud auth application-default login` (or `GOOGLE_APPLICATION_CREDENTIALS`\n   for service accounts). Listing instances\/databases requires\n   `roles\/spanner.viewer`, inspecting DDL requires\n   `roles\/spanner.databaseReader`, and applying `CREATE VIEW` \/\n   `CREATE PROPERTY GRAPH` DDL requires `roles\/spanner.databaseAdmin`.\n4. **Instance Region & Pricing**: For sandbox test instances, default to\n   `regional-us-central1` unless specified otherwise (see\n   [Spanner instance configurations](https:\/\/docs.cloud.google.com\/spanner\/docs\/instance-configurations.md.txt),\n   [Google Cloud locations](https:\/\/cloud.google.com\/about\/locations),\n   [Spanner pricing](https:\/\/cloud.google.com\/spanner\/pricing), and\n   [Google Cloud pricing](https:\/\/cloud.google.com\/pricing)).\n\n---\n\n## Core Principles\n\n1. **Zero Data Duplication**: Spanner Graph maps existing relational tables or\n   SQL views directly into graph nodes and edges via `CREATE PROPERTY GRAPH`\n   metadata\u2014without copying data or breaking existing SQL applications.\n2. **Preserve Existing Tables**: Treat all existing relational tables as\n   read-only inputs. Do not drop, rename, or alter existing columns or primary\n   keys when adding a property graph view. If an implicit relationship requires\n   key transformation (for example, unnesting an array or casting mismatched key\n   types), define a new SQL bridge view\n   (`CREATE VIEW ... SQL SECURITY INVOKER AS ...` by default, or\n   `SQL SECURITY DEFINER` when row-level access control is needed) and bind the\n   edge or node to that view.\n3. **100% Table Accounting**: Account for every relational table in the input\n   schema\u2014either mapped into `NODE TABLES` \/ `EDGE TABLES` or explicitly listed\n   as excluded (such as pure system audit logs, schema migration state tables,\n   or unlinked lookup tables).\n\n---\n\n## Step-by-Step Conversion Workflow\n\n### Step 1: Discover or Parse the Relational Schema\n\n- **If the user provides DDL statements in the prompt**, parse all\n  `CREATE TABLE`, `PRIMARY KEY`, `INTERLEAVE IN PARENT`, and `FOREIGN KEY`\n  definitions directly.\n- **If the user provides a live Spanner instance and database ID** (or a Google\n  Cloud Console URL containing\n  `instances\/{instance_id}\/databases\/{database_id}?project={project_id}`),\n  extract `project`, `instance`, and `database` and retrieve the live DDL using\n  the read-only `gcloud` command:\n\n  ```bash\n  gcloud spanner databases ddl describe {database_id} \\\n    --instance={instance_id} \\\n    --project={project_id}\n  ```\n\n  - **Live-Database Safety Rule**: `gcloud spanner databases ddl describe` is\n    read-only and safe to run automatically, whereas applying `CREATE VIEW` or\n    `CREATE OR REPLACE PROPERTY GRAPH` via `gcloud spanner databases ddl update`\n    mutates the live database\u2014always ask for **explicit user confirmation**\n    before running `gcloud spanner databases ddl update` (and state this\n    confirmation requirement clearly in your response even if `ddl describe`\n    fails due to missing credentials or network access).\n  - See [references\/cloud-spanner-guide.md](references\/cloud-spanner-guide.md)\n    for environment discovery, emulator setup, and verification workflows.\n\n### Step 2: Classify Relational Tables into Nodes and Edges\n\nApply the structural classification rules in\n[references\/patterns.md](references\/patterns.md):\n\n1. **Core Entity Tables -> `NODE TABLES`**:\n   - Tables representing domain nouns (`Users`, `Accounts`, `Products`,\n     `Devices`, `Documents`) become node tables.\n   - Use the table's full `PRIMARY KEY` as the node `KEY (...)`.\n2. **Pure or Attributed M:N Junction Tables -> `EDGE TABLES`**:\n   - Tables that link two entity keys (such as\n     `ProjectAssignments(emp_id, project_id)` or `WireTransfers(transfer_id)`\n     with `src_account_id` and `dst_account_id`) become edge tables.\n   - If the table also represents an entity referenced by other tables (for\n     example, `Orders` is a child of `Customers` and a parent of `OrderItems`),\n     map `Orders` as **both** a `NODE TABLE` (`Orders AS OrderNode`) and an\n     `EDGE TABLE` (`Orders AS PlacedOrder`).\n3. **1:N Foreign Keys and Interleaved Parent-Child Tables -> `EDGE TABLES`\n   (`Table AS Edge`)**:\n   - An entity table `B` with a foreign key (or interleaved parent key prefix)\n     referencing `A` can simultaneously act as a `NODE TABLE` (`B AS NodeB`) and\n     an `EDGE TABLE` (`B AS EdgeBA`) connecting `B` to `A` (or `A` to `B`).\n   - **Self-Referential Hierarchies**: A table like\n     `Employees(emp_id, manager_id)` maps to `Employees AS Employee` in\n     `NODE TABLES` and `Employees AS ReportsToEdge` in `EDGE TABLES`\n     (`SOURCE KEY (emp_id) REFERENCES Employee(emp_id)` and\n     `DESTINATION KEY (manager_id) REFERENCES Employee(emp_id)`).\n4. **Implicit Relationships (Arrays, JSON, Polymorphic Keys) -> Bridge Views**:\n   - When relationships are embedded in `ARRAY<INT64>` columns, JSON fields, or\n     type-mismatched keys (`INT64` vs. `STRING`), create a SQL bridge view that\n     flattens and projects `(edge_key, src_key, dst_key)` and register the view\n     in `EDGE TABLES` with an explicit `KEY (...)`.\n   - **View Security (`INVOKER` vs. `DEFINER`)**: Every Spanner view requires a\n     `SQL SECURITY` clause. `SQL SECURITY INVOKER` is the common default when\n     callers already hold permissions on the underlying tables, whereas\n     `SQL SECURITY DEFINER` is supported when you need row-level \/ fine-grained\n     access control so callers can query the graph view without direct\n     base-table grants.\n   - **View Key Uniqueness & `validate_element_key_uniqueness`**: By default,\n     Spanner syntactically verifies that a view's declared `KEY` is unique\n     (either a single base table's primary key or matched by `SELECT DISTINCT` \/\n     `GROUP BY`), failing otherwise with\n     `cannot verify the specified element key ... is unique`. Use\n     `SELECT DISTINCT` (or `GROUP BY` the key columns) when inputs can contain\n     duplicate keys (such as duplicate elements inside an `ARRAY`); if you know\n     the view's `KEY` is **already semantically unique** (for example, a\n     key-preserving `JOIN` or `UNNEST(...) WITH OFFSET`), you can instead append\n     `OPTIONS (validate_element_key_uniqueness = false)` to\n     `CREATE PROPERTY GRAPH` to skip syntactic validation without extra\n     `DISTINCT` \/ `GROUP BY` overhead (you remain responsible for ensuring keys\n     are unique in data).\n\n### Step 3: Decide Graph Scoping (Unified vs. Multi-Graph)\n\n- **Default to 1 Unified Property Graph** when tables share a connected domain.\n- **Recommend Multiple Property Graphs** only when the database contains\n  completely disconnected business domains or exceeds ~12+ distinct node\/edge\n  types where domain-specific subgraphs improve query ergonomics.\n\n### Step 4: Author the `CREATE OR REPLACE PROPERTY GRAPH` DDL\n\nFollow the exact syntax and structural invariants in\n[references\/spanner-graph-ddl-syntax.md](references\/spanner-graph-ddl-syntax.md)\nand [references\/structural-invariants.md](references\/structural-invariants.md):\n\n```sql\nCREATE OR REPLACE PROPERTY GRAPH GraphName\n  NODE TABLES (\n    TableName AS NodeAlias\n      KEY (pk_col1, pk_col2)\n      LABEL NodeLabel\n  )\n  EDGE TABLES (\n    EdgeTableName AS EdgeAlias\n      KEY (edge_pk_col1, edge_pk_col2)\n      SOURCE KEY (src_fk_col1) REFERENCES SourceNodeAlias(src_pk_col1)\n      DESTINATION KEY (dst_fk_col1) REFERENCES DestNodeAlias(dst_pk_col1)\n      LABEL EdgeLabel\n  );\n```\n\n#### Critical DDL Invariants Checklist\n\n- `NODE TABLES` must be declared **before** `EDGE TABLES`.\n- Every `NodeAlias` and `EdgeAlias` must be **globally unique** across the\n  entire `CREATE PROPERTY GRAPH` statement (if a table is used as both a node\n  and an edge, give them distinct aliases, e.g., `Orders AS OrderNode` and\n  `Orders AS PlacedOrderEdge`).\n- **Decouple Edge Identity (`KEY`) from Endpoint Topology (`SOURCE KEY` \/\n  `DESTINATION KEY`)**:\n  - `KEY (...)` uniquely identifies the edge row in the backing table or view\n    (for example, `KEY (transfer_id)` or `KEY (src_id, dst_id, transfer_ts)`),\n    while `SOURCE KEY` and `DESTINATION KEY` specify the endpoints. Spanner\n    enforces uniqueness: on a table, a custom `KEY` must contain all primary key\n    columns or match a `UNIQUE` index (so `KEY (src_id, dst_id, transfer_ts)` on\n    a table whose primary key is `transfer_id` fails unless such an index\n    exists). Rows where any `KEY`, `SOURCE KEY`, or `DESTINATION KEY` column is\n    `NULL` are silently skipped by `MATCH`.\n  - In `SOURCE KEY (...) REFERENCES NodeAlias(...)` and\n    `DESTINATION KEY (...) REFERENCES NodeAlias(...)`, the target after\n    `REFERENCES` must be the **`NodeAlias`** (not the underlying relational\n    table name if an alias was used, and not the `LABEL` name), and the column\n    count and data types must match the referenced node's `KEY` 1-to-1. Spanner\n    does not always enforce the count: with an explicit column list it accepts a\n    partial composite key, and each edge then silently matches every node\n    sharing that value.\n- **Property Exposure (Default `ALL COLUMNS` vs. Explicit `PROPERTIES (...)` \/\n  `NO PROPERTIES`)**:\n  - By default, omitting the `PROPERTIES` clause (implicit\n    `PROPERTIES ALL COLUMNS`) exposes all columns of the input table and is\n    concise when a table has its own label and non-conflicting column types.\n  - Use explicit `PROPERTIES (col1 [AS alias], ...)`,\n    `PROPERTIES ALL COLUMNS EXCEPT (...)`, or `NO PROPERTIES` in four\n    relational-conversion cases: (1) **cross-table property type conflicts**\n    (aliasing colliding column names), (2) **shared `LABEL`s** across tables,\n    (3) **dual `Table AS Node` + `Table AS Edge` or pure junction mappings**\n    (`NO PROPERTIES` or edge-only columns so node attributes are not duplicated\n    onto edges), and (4) **excluding internal\/sensitive columns or avoiding\n    duplicate exposure of a `DYNAMIC PROPERTIES (json_col)` column**\n    (`PROPERTIES ALL COLUMNS EXCEPT (json_col)`).\n  - If two elements share the same `LABEL` name, they must expose the **exact\n    same set of property names and data types** under that label.\n  - A property name must have **one data type across the whole graph**, even\n    under different labels or on node vs. edge tables (for example, `id INT64`\n    in one table and `id STRING` in another fails with\n    `The property declaration of 'id' has type conflicts`). Alias\n    (`id AS user_id`) or `CAST` one side.\n- **Optional Reverse Edge Alias (Naming Only)**:\n  - A single physical edge table can be registered a second time in\n    `EDGE TABLES` under a reverse alias (swapping `SOURCE KEY` and\n    `DESTINATION KEY`) when the domain needs a distinct directional label. Don't\n    add one for performance: for undirected traversals use `-[e:LABEL]-` plus a\n    reverse index; querying a swapped-key alias as a label union forces a union\n    across two edge definitions at every hop, which is slower than `-[e:LABEL]-`\n    on quantified paths.\n\n### Step 5: Verify the DDL and Provide Recommendations\n\n1. **Verify the DDL** (when a target Spanner database or local emulator is\n   available; see\n   [references\/cloud-spanner-guide.md](references\/cloud-spanner-guide.md)).\n   Never apply DDL to a shared or production database without explicit user\n   confirmation.\n2. **Present a Structured 5-Part Deliverable** (modeled in\n   [references\/synthesized-conversions.md](references\/synthesized-conversions.md)):\n   - **Part 1: Graph Extension Summary & Mapping Matrix** (100% accounting of\n     included and excluded tables).\n   - **Part 2: Complete Executable Spanner Graph DDL** (any required\n     `CREATE VIEW ... SQL SECURITY {INVOKER | DEFINER}` statements followed by\n     `CREATE OR REPLACE PROPERTY GRAPH`).\n   - **Part 3: Performance & Indexing Recommendations** (such as\n     reverse-traversal secondary indexes\n     `ON EdgeTable (dst_key, src_key) INTERLEAVE IN DestNodeTable` or\n     `STORING (...)`, simplifying over-wide composite keys on junction tables,\n     and high-degree hub foreign-key considerations).\n   - **Part 4: Sample ISO GQL Queries** using\n     `GRAPH GraphName MATCH ... RETURN ...` (see\n     [references\/gql-cheat-sheet.md](references\/gql-cheat-sheet.md)).\n   - **Part 5: Schema Verification Status**.\n\n---\n\n## Reference Documentation\n\n- **[Spanner Discovery Guide](references\/cloud-spanner-guide.md)**: Extracting\n  DDL from Spanner via `gcloud`, parsing console URLs, and validating\n  `CREATE PROPERTY GRAPH` on a sandbox or Spanner Emulator.\n- **[Relational-to-Graph Mapping Patterns](references\/patterns.md)**: Detailed\n  rules for classifying entity tables, junction tables, interleaved hierarchies,\n  self-referential FKs, polymorphic tables, and SQL bridge views.\n- **[Spanner Graph DDL Syntax](references\/spanner-graph-ddl-syntax.md)**: Exact\n  BNF grammar and syntax rules for `CREATE PROPERTY GRAPH`, `NODE TABLES`,\n  `EDGE TABLES`, `KEY`, and `PROPERTIES`.\n- **[Structural Invariants](references\/structural-invariants.md)**: How to\n  prevent and fix the 8 most common Spanner Graph DDL mistakes (alias\n  collisions, shared-label and graph-wide property type conflicts, partial or\n  mismatched key references, unverifiable view keys, and custom key uniqueness),\n  with the actual Spanner error messages.\n- **[ISO GQL Cheat Sheet](references\/gql-cheat-sheet.md)**: Quick syntax\n  reference for writing valid Spanner Graph ISO GQL queries (`MATCH`,\n  `WHERE`\/`FILTER`, quantified paths `{m,n}`, `NEXT`, `RETURN`).\n- **[Synthesized Examples](references\/synthesized-conversions.md)**: Four\n  complete relational-to-property-graph conversion examples (E-Commerce,\n  Financial AML, Enterprise Org Matrix, and Threat Intelligence).\n- **Official Spanner Graph Schema Design Documentation**:\n  [Spanner Graph schema design best practices](https:\/\/docs.cloud.google.com\/spanner\/docs\/graph\/best-practices-designing-schema.md.txt)\n\nIf you need product information that's not found in these references, use the\n`search_documents` tool of the Developer Knowledge MCP server.\n","use_cases":["Mapping existing Spanner tables to a graph","Identifying node and edge candidates from relational tables","Creating SQL bridge views for implicit relationships","Mapping polymorphic or self-referential tables","Troubleshooting `CREATE PROPERTY GRAPH` DDL compiler errors"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/google\/skills\/blob\/c413c1fdc1714f2e4ae44a449b9744348197119c\/skills\/cloud\/spanner-relational-to-graph\/SKILL.md","source_commit":"c413c1fdc1714f2e4ae44a449b9744348197119c","license":null,"version":null,"listing_approved_at":"2026-11-27","created_at":"2026-11-26T11:17:01.000000Z","updated_at":"2026-11-27T07:43:09.000000Z","seo_title":"Spanner Relational to Graph Conversion","seo_description":"Convert Spanner relational schemas to property graphs for graph analysis without modifying existing tables.","seo_keywords":["Spanner relational to graph","Spanner graph schema conversion","Spanner property graph creation","Spanner DDL to graph","Spanner graph mapping"]}}