Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install spanner-relational-to-graph@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin spanner-relational-to-graph v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install spanner-relational-to-graph

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/spanner-relational-to-graph/

Extract the ZIP to .github/skills/ in your repo. The folder name must match spanner-relational-to-graph for Copilot to auto-discover it.

Skill Files (8)

SKILL.md 15.9 KB
---
name: spanner-relational-to-graph
metadata:
  version: "1.0.0"
  category: Databases
description: >-
  Analyzes existing Spanner relational schemas on Google Cloud (DDL, foreign
  keys, interleaved tables, and junction tables) and generates
  `CREATE PROPERTY GRAPH` DDL statements (`NODE TABLES`, `EDGE TABLES`) without
  modifying underlying relational tables. Use when mapping existing Spanner
  tables to a Spanner Graph, identifying node and edge candidates from
  relational tables, creating SQL bridge views for implicit `ARRAY`/`JSON` or
  type-mismatched relationships, mapping polymorphic or self-referential tables,
  or troubleshooting `CREATE PROPERTY GRAPH` DDL compiler errors. Don't use for
  greenfield physical table design (use spanner-graph-schema-best-practices) or
  tuning slow ISO GQL queries (use spanner-graph-query-tuning).
---

# Spanner Relational-to-Property-Graph Schema Conversion

Convert an existing Spanner relational schema into a valid, production-ready
`CREATE OR REPLACE PROPERTY GRAPH` DDL definition while keeping existing
relational tables intact.

## Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you MUST
read and follow the instructions in
[Usage Attribution](references/attribution.md).

## Prerequisites & Cloud Environment Setup

When inspecting a live Spanner instance or verifying DDL (see `spanner-basics`
for general Spanner instance provisioning and MCP setup):

1. **Google Cloud SDK (`gcloud`)**: Ensure the CLI is installed (see
   [Install the Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)).
2. **Project, Billing & API**: Verify an active Google Cloud project with
   billing enabled (required even when provisioning a free trial instance) is
   configured (`gcloud config set project {project_id}`) and, after the user
   confirms, enable the Spanner API
   (`gcloud services enable spanner.googleapis.com`). Ask the user before
   changing the active project, billing, or enabled APIs, or creating or
   deleting instances, because these commands change the user's Google Cloud
   environment and can incur costs.
3. **Authentication & IAM Roles**: Authenticate via `gcloud auth login` or
   `gcloud auth application-default login` (or `GOOGLE_APPLICATION_CREDENTIALS`
   for service accounts). Listing instances/databases requires
   `roles/spanner.viewer`, inspecting DDL requires
   `roles/spanner.databaseReader`, and applying `CREATE VIEW` /
   `CREATE PROPERTY GRAPH` DDL requires `roles/spanner.databaseAdmin`.
4. **Instance Region & Pricing**: For sandbox test instances, default to
   `regional-us-central1` unless specified otherwise (see
   [Spanner instance configurations](https://docs.cloud.google.com/spanner/docs/instance-configurations.md.txt),
   [Google Cloud locations](https://cloud.google.com/about/locations),
   [Spanner pricing](https://cloud.google.com/spanner/pricing), and
   [Google Cloud pricing](https://cloud.google.com/pricing)).

---

## Core Principles

1. **Zero Data Duplication**: Spanner Graph maps existing relational tables or
   SQL views directly into graph nodes and edges via `CREATE PROPERTY GRAPH`
   metadata—without copying data or breaking existing SQL applications.
2. **Preserve Existing Tables**: Treat all existing relational tables as
   read-only inputs. Do not drop, rename, or alter existing columns or primary
   keys when adding a property graph view. If an implicit relationship requires
   key transformation (for example, unnesting an array or casting mismatched key
   types), define a new SQL bridge view
   (`CREATE VIEW ... SQL SECURITY INVOKER AS ...` by default, or
   `SQL SECURITY DEFINER` when row-level access control is needed) and bind the
   edge or node to that view.
3. **100% Table Accounting**: Account for every relational table in the input
   schema—either mapped into `NODE TABLES` / `EDGE TABLES` or explicitly listed
   as excluded (such as pure system audit logs, schema migration state tables,
   or unlinked lookup tables).

---

## Step-by-Step Conversion Workflow

### Step 1: Discover or Parse the Relational Schema

- **If the user provides DDL statements in the prompt**, parse all
  `CREATE TABLE`, `PRIMARY KEY`, `INTERLEAVE IN PARENT`, and `FOREIGN KEY`
  definitions directly.
- **If the user provides a live Spanner instance and database ID** (or a Google
  Cloud Console URL containing
  `instances/{instance_id}/databases/{database_id}?project={project_id}`),
  extract `project`, `instance`, and `database` and retrieve the live DDL using
  the read-only `gcloud` command:

  ```bash
  gcloud spanner databases ddl describe {database_id} \
    --instance={instance_id} \
    --project={project_id}
  ```

  - **Live-Database Safety Rule**: `gcloud spanner databases ddl describe` is
    read-only and safe to run automatically, whereas applying `CREATE VIEW` or
    `CREATE OR REPLACE PROPERTY GRAPH` via `gcloud spanner databases ddl update`
    mutates the live database—always ask for **explicit user confirmation**
    before running `gcloud spanner databases ddl update` (and state this
    confirmation requirement clearly in your response even if `ddl describe`
    fails due to missing credentials or network access).
  - See [references/cloud-spanner-guide.md](references/cloud-spanner-guide.md)
    for environment discovery, emulator setup, and verification workflows.

### Step 2: Classify Relational Tables into Nodes and Edges

Apply the structural classification rules in
[references/patterns.md](references/patterns.md):

1. **Core Entity Tables -> `NODE TABLES`**:
   - Tables representing domain nouns (`Users`, `Accounts`, `Products`,
     `Devices`, `Documents`) become node tables.
   - Use the table's full `PRIMARY KEY` as the node `KEY (...)`.
2. **Pure or Attributed M:N Junction Tables -> `EDGE TABLES`**:
   - Tables that link two entity keys (such as
     `ProjectAssignments(emp_id, project_id)` or `WireTransfers(transfer_id)`
     with `src_account_id` and `dst_account_id`) become edge tables.
   - If the table also represents an entity referenced by other tables (for
     example, `Orders` is a child of `Customers` and a parent of `OrderItems`),
     map `Orders` as **both** a `NODE TABLE` (`Orders AS OrderNode`) and an
     `EDGE TABLE` (`Orders AS PlacedOrder`).
3. **1:N Foreign Keys and Interleaved Parent-Child Tables -> `EDGE TABLES`
   (`Table AS Edge`)**:
   - An entity table `B` with a foreign key (or interleaved parent key prefix)
     referencing `A` can simultaneously act as a `NODE TABLE` (`B AS NodeB`) and
     an `EDGE TABLE` (`B AS EdgeBA`) connecting `B` to `A` (or `A` to `B`).
   - **Self-Referential Hierarchies**: A table like
     `Employees(emp_id, manager_id)` maps to `Employees AS Employee` in
     `NODE TABLES` and `Employees AS ReportsToEdge` in `EDGE TABLES`
     (`SOURCE KEY (emp_id) REFERENCES Employee(emp_id)` and
     `DESTINATION KEY (manager_id) REFERENCES Employee(emp_id)`).
4. **Implicit Relationships (Arrays, JSON, Polymorphic Keys) -> Bridge Views**:
   - When relationships are embedded in `ARRAY<INT64>` columns, JSON fields, or
     type-mismatched keys (`INT64` vs. `STRING`), create a SQL bridge view that
     flattens and projects `(edge_key, src_key, dst_key)` and register the view
     in `EDGE TABLES` with an explicit `KEY (...)`.
   - **View Security (`INVOKER` vs. `DEFINER`)**: Every Spanner view requires a
     `SQL SECURITY` clause. `SQL SECURITY INVOKER` is the common default when
     callers already hold permissions on the underlying tables, whereas
     `SQL SECURITY DEFINER` is supported when you need row-level / fine-grained
     access control so callers can query the graph view without direct
     base-table grants.
   - **View Key Uniqueness & `validate_element_key_uniqueness`**: By default,
     Spanner syntactically verifies that a view's declared `KEY` is unique
     (either a single base table's primary key or matched by `SELECT DISTINCT` /
     `GROUP BY`), failing otherwise with
     `cannot verify the specified element key ... is unique`. Use
     `SELECT DISTINCT` (or `GROUP BY` the key columns) when inputs can contain
     duplicate keys (such as duplicate elements inside an `ARRAY`); if you know
     the view's `KEY` is **already semantically unique** (for example, a
     key-preserving `JOIN` or `UNNEST(...) WITH OFFSET`), you can instead append
     `OPTIONS (validate_element_key_uniqueness = false)` to
     `CREATE PROPERTY GRAPH` to skip syntactic validation without extra
     `DISTINCT` / `GROUP BY` overhead (you remain responsible for ensuring keys
     are unique in data).

### Step 3: Decide Graph Scoping (Unified vs. Multi-Graph)

- **Default to 1 Unified Property Graph** when tables share a connected domain.
- **Recommend Multiple Property Graphs** only when the database contains
  completely disconnected business domains or exceeds ~12+ distinct node/edge
  types where domain-specific subgraphs improve query ergonomics.

### Step 4: Author the `CREATE OR REPLACE PROPERTY GRAPH` DDL

Follow the exact syntax and structural invariants in
[references/spanner-graph-ddl-syntax.md](references/spanner-graph-ddl-syntax.md)
and [references/structural-invariants.md](references/structural-invariants.md):

```sql
CREATE OR REPLACE PROPERTY GRAPH GraphName
  NODE TABLES (
    TableName AS NodeAlias
      KEY (pk_col1, pk_col2)
      LABEL NodeLabel
  )
  EDGE TABLES (
    EdgeTableName AS EdgeAlias
      KEY (edge_pk_col1, edge_pk_col2)
      SOURCE KEY (src_fk_col1) REFERENCES SourceNodeAlias(src_pk_col1)
      DESTINATION KEY (dst_fk_col1) REFERENCES DestNodeAlias(dst_pk_col1)
      LABEL EdgeLabel
  );
```

#### Critical DDL Invariants Checklist

- `NODE TABLES` must be declared **before** `EDGE TABLES`.
- Every `NodeAlias` and `EdgeAlias` must be **globally unique** across the
  entire `CREATE PROPERTY GRAPH` statement (if a table is used as both a node
  and an edge, give them distinct aliases, e.g., `Orders AS OrderNode` and
  `Orders AS PlacedOrderEdge`).
- **Decouple Edge Identity (`KEY`) from Endpoint Topology (`SOURCE KEY` /
  `DESTINATION KEY`)**:
  - `KEY (...)` uniquely identifies the edge row in the backing table or view
    (for example, `KEY (transfer_id)` or `KEY (src_id, dst_id, transfer_ts)`),
    while `SOURCE KEY` and `DESTINATION KEY` specify the endpoints. Spanner
    enforces uniqueness: on a table, a custom `KEY` must contain all primary key
    columns or match a `UNIQUE` index (so `KEY (src_id, dst_id, transfer_ts)` on
    a table whose primary key is `transfer_id` fails unless such an index
    exists). Rows where any `KEY`, `SOURCE KEY`, or `DESTINATION KEY` column is
    `NULL` are silently skipped by `MATCH`.
  - In `SOURCE KEY (...) REFERENCES NodeAlias(...)` and
    `DESTINATION KEY (...) REFERENCES NodeAlias(...)`, the target after
    `REFERENCES` must be the **`NodeAlias`** (not the underlying relational
    table name if an alias was used, and not the `LABEL` name), and the column
    count and data types must match the referenced node's `KEY` 1-to-1. Spanner
    does not always enforce the count: with an explicit column list it accepts a
    partial composite key, and each edge then silently matches every node
    sharing that value.
- **Property Exposure (Default `ALL COLUMNS` vs. Explicit `PROPERTIES (...)` /
  `NO PROPERTIES`)**:
  - By default, omitting the `PROPERTIES` clause (implicit
    `PROPERTIES ALL COLUMNS`) exposes all columns of the input table and is
    concise when a table has its own label and non-conflicting column types.
  - Use explicit `PROPERTIES (col1 [AS alias], ...)`,
    `PROPERTIES ALL COLUMNS EXCEPT (...)`, or `NO PROPERTIES` in four
    relational-conversion cases: (1) **cross-table property type conflicts**
    (aliasing colliding column names), (2) **shared `LABEL`s** across tables,
    (3) **dual `Table AS Node` + `Table AS Edge` or pure junction mappings**
    (`NO PROPERTIES` or edge-only columns so node attributes are not duplicated
    onto edges), and (4) **excluding internal/sensitive columns or avoiding
    duplicate exposure of a `DYNAMIC PROPERTIES (json_col)` column**
    (`PROPERTIES ALL COLUMNS EXCEPT (json_col)`).
  - If two elements share the same `LABEL` name, they must expose the **exact
    same set of property names and data types** under that label.
  - A property name must have **one data type across the whole graph**, even
    under different labels or on node vs. edge tables (for example, `id INT64`
    in one table and `id STRING` in another fails with
    `The property declaration of 'id' has type conflicts`). Alias
    (`id AS user_id`) or `CAST` one side.
- **Optional Reverse Edge Alias (Naming Only)**:
  - A single physical edge table can be registered a second time in
    `EDGE TABLES` under a reverse alias (swapping `SOURCE KEY` and
    `DESTINATION KEY`) when the domain needs a distinct directional label. Don't
    add one for performance: for undirected traversals use `-[e:LABEL]-` plus a
    reverse index; querying a swapped-key alias as a label union forces a union
    across two edge definitions at every hop, which is slower than `-[e:LABEL]-`
    on quantified paths.

### Step 5: Verify the DDL and Provide Recommendations

1. **Verify the DDL** (when a target Spanner database or local emulator is
   available; see
   [references/cloud-spanner-guide.md](references/cloud-spanner-guide.md)).
   Never apply DDL to a shared or production database without explicit user
   confirmation.
2. **Present a Structured 5-Part Deliverable** (modeled in
   [references/synthesized-conversions.md](references/synthesized-conversions.md)):
   - **Part 1: Graph Extension Summary & Mapping Matrix** (100% accounting of
     included and excluded tables).
   - **Part 2: Complete Executable Spanner Graph DDL** (any required
     `CREATE VIEW ... SQL SECURITY {INVOKER | DEFINER}` statements followed by
     `CREATE OR REPLACE PROPERTY GRAPH`).
   - **Part 3: Performance & Indexing Recommendations** (such as
     reverse-traversal secondary indexes
     `ON EdgeTable (dst_key, src_key) INTERLEAVE IN DestNodeTable` or
     `STORING (...)`, simplifying over-wide composite keys on junction tables,
     and high-degree hub foreign-key considerations).
   - **Part 4: Sample ISO GQL Queries** using
     `GRAPH GraphName MATCH ... RETURN ...` (see
     [references/gql-cheat-sheet.md](references/gql-cheat-sheet.md)).
   - **Part 5: Schema Verification Status**.

---

## Reference Documentation

- **[Spanner Discovery Guide](references/cloud-spanner-guide.md)**: Extracting
  DDL from Spanner via `gcloud`, parsing console URLs, and validating
  `CREATE PROPERTY GRAPH` on a sandbox or Spanner Emulator.
- **[Relational-to-Graph Mapping Patterns](references/patterns.md)**: Detailed
  rules for classifying entity tables, junction tables, interleaved hierarchies,
  self-referential FKs, polymorphic tables, and SQL bridge views.
- **[Spanner Graph DDL Syntax](references/spanner-graph-ddl-syntax.md)**: Exact
  BNF grammar and syntax rules for `CREATE PROPERTY GRAPH`, `NODE TABLES`,
  `EDGE TABLES`, `KEY`, and `PROPERTIES`.
- **[Structural Invariants](references/structural-invariants.md)**: How to
  prevent and fix the 8 most common Spanner Graph DDL mistakes (alias
  collisions, shared-label and graph-wide property type conflicts, partial or
  mismatched key references, unverifiable view keys, and custom key uniqueness),
  with the actual Spanner error messages.
- **[ISO GQL Cheat Sheet](references/gql-cheat-sheet.md)**: Quick syntax
  reference for writing valid Spanner Graph ISO GQL queries (`MATCH`,
  `WHERE`/`FILTER`, quantified paths `{m,n}`, `NEXT`, `RETURN`).
- **[Synthesized Examples](references/synthesized-conversions.md)**: Four
  complete relational-to-property-graph conversion examples (E-Commerce,
  Financial AML, Enterprise Org Matrix, and Threat Intelligence).
- **Official Spanner Graph Schema Design Documentation**:
  [Spanner Graph schema design best practices](https://docs.cloud.google.com/spanner/docs/graph/best-practices-designing-schema.md.txt)

If you need product information that's not found in these references, use the
`search_documents` tool of the Developer Knowledge MCP server.
references/
attribution.md 1.9 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with this
skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:spanner-relational-to-graph)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include `agent-skills/1.0 (skill:spanner-relational-to-graph)` in
    the `User-Agent` header. If a `User-Agent` header is already specified,
    append this string to the end of it rather than overwriting existing
    `User-Agent` data — the collection pipeline parses the
    `agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
    attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:spanner-relational-to-graph)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
cloud-spanner-guide.md 4.0 KB
# Spanner Schema Discovery & DDL Verification Guide

## 1. Extracting Parameters from Google Cloud Console URLs

If a user supplies a Google Cloud Console link to a Spanner database, extract
the target `{instance_id}`, `{database_id}`, and `{project_id}` directly from
the URL pattern:

- **URL Pattern**:
  `https://console.cloud.google.com/spanner/instances/{instance_id}/databases/{database_id}?project={project_id}`
  (or sub-paths such as `/schema`, `/graph`, `/query`).
- Extract:
  - `{instance_id}`: segment immediately following `/instances/`
  - `{database_id}`: segment immediately following `/databases/`
  - `{project_id}`: value of the `project=` query parameter

## 2. Discovering Relational Schema DDL via `gcloud`

1. **When `{project_id}`, `{instance_id}`, and `{database_id}` are known**,
   fetch the full relational schema DDL directly (requires
   `roles/spanner.databaseReader`):
   ```bash
   gcloud spanner databases ddl describe {database_id} \
     --instance={instance_id} \
     --project={project_id}
   ```

2. **When `{instance_id}` or `{database_id}` are omitted**, discover them
   interactively (requires `roles/spanner.viewer`):
   ```bash
   # Check current default project
   gcloud config get-value project

   # List Spanner instances in the project
   gcloud spanner instances list --project={project_id}

   # List databases in the target instance
   gcloud spanner databases list --instance={instance_id} --project={project_id}
   ```
   If multiple databases exist and the target is ambiguous, present the
   discovered list and ask the user which database to target before proceeding.

## 3. Safe DDL Verification Workflow

### Safety Guardrail for Live Databases

- **Read-Only Discovery**: `gcloud spanner databases ddl describe` and
  `gcloud spanner instances/databases list` are read-only and safe to run
  automatically.
- **Explicit Confirmation for Schema Updates**: Applying `CREATE VIEW` or
  `CREATE OR REPLACE PROPERTY GRAPH` via `gcloud spanner databases ddl update`
  mutates database metadata (requires `roles/spanner.databaseAdmin`). Always ask
  for explicit user confirmation before executing `ddl update` against a shared
  or production Spanner instance.

### Option A: Applying DDL on an Authorized Spanner Database
Once the user confirms target execution:
```bash
gcloud spanner databases ddl update {database_id} \
  --instance={instance_id} \
  --project={project_id} \
  --ddl="$(cat graph_schema.sql)"
```

### Option B: Hermetic Verification on the Local Spanner Emulator

Prefer Option A on a user-confirmed Spanner instance whenever one is available
(for example, applying the DDL to an empty development database on the same
instance), because the emulator doesn't reproduce every engine-specific
validation. Use the emulator only as a fallback when no Spanner instance is
available, and tell the user that emulator validation is a best-effort check
that should be repeated on a real instance before production use.

To validate the combined relational + property graph DDL without touching a
remote database, follow the official
[Spanner Emulator guide](https://docs.cloud.google.com/spanner/docs/emulator.md.txt)
(if the emulator isn't installed, ask the user before installing it). Create an
isolated `gcloud` configuration (`--no-activate`) and pass
`--configuration=emulator` on every command so verification never reaches a real
instance, apply the combined DDL via `gcloud spanner databases create` with
`--ddl-file=combined_schema_and_graph.sql`, and delete the temporary emulator
database and instance when finished.

### Smoke-Testing the Property Graph with GQL
After applying the DDL on a sandbox or emulator, run a lightweight 1-hop ISO GQL
query to confirm element bindings (on the emulator, replace
`--project={project_id}` with `--configuration=emulator`):
```bash
gcloud spanner databases execute-sql {database_id} \
  --instance={instance_id} \
  --project={project_id} \
  --sql="GRAPH MyGraph MATCH (n)-[e]->(m) RETURN LABELS(n)[SAFE_OFFSET(0)] AS src_label, LABELS(e)[SAFE_OFFSET(0)] AS edge_label, LABELS(m)[SAFE_OFFSET(0)] AS dst_label LIMIT 5"
```
gql-cheat-sheet.md 3.3 KB
# Spanner ISO GQL Cheat Sheet

## 1. Basic Query Structure

Every Spanner Graph query begins with `GRAPH {graph_name}` followed by one or
more `MATCH`, `FILTER`/`WHERE`, `LET`, `RETURN`, and optional `NEXT` clauses:

```sql
GRAPH ECommerceGraph
MATCH (c:Customer {country: 'US'})-[p:PLACED]->(o:`Order`)
WHERE o.total_usd > 100
RETURN c.customer_id, c.name, o.order_id, o.total_usd
ORDER BY o.total_usd DESC
LIMIT 20;
```

## 2. Node and Edge Pattern Syntax

- **Node pattern**: `(alias:Label {prop: value})`
- **Directed outgoing edge**: `-[edge_alias:EDGE_LABEL]->`
- **Directed incoming edge**: `<-[edge_alias:EDGE_LABEL]-`
- **Undirected / any-direction match**: `-[edge_alias:EDGE_LABEL]-`
  (`<-[e:LABEL]->` is not valid Spanner GQL syntax)
- **Label disjunction (OR)**: `(n:Customer|Vendor)` or
  `-[e:TRANSFERRED_TO|PAID]->`
- **Escaping reserved words**: Wrap labels that collide with SQL/GQL reserved
  keywords in backticks (for example, `` (o:`Order`) ``, `` (g:`Group`) ``).

## 3. Variable-Length Quantified Path Patterns (`{m, n}`)

To traverse between `m` and `n` hops along an edge pattern, append `{m, n}` to
the edge or parenthesized path pattern. In Spanner Graph, the upper bound `n`
must be a finite integer:

```sql
-- 1 to 4 hops along a reporting hierarchy
GRAPH EnterpriseOrgGraph
MATCH (emp:Employee)-[r:REPORTS_TO]->{1, 4}(mgr:Employee)
WHERE mgr.job_title = 'VP of Engineering'
RETURN emp.full_name AS employee_name, mgr.full_name AS manager_name, ARRAY_LENGTH(r) AS reporting_depth;
```

- Inside a quantified path `{m, n}`, the edge variable `r` is bound as a **group
  variable (`ARRAY` of edges)** across the matched path. Use `ARRAY_LENGTH(r)`
  to inspect hop count.
- Output column names must be unique: `RETURN emp.full_name, mgr.full_name`
  fails with `Ambiguous name: full_name`, so alias duplicates.

## 4. Chaining Multi-Stage Queries with `NEXT`

Use `NEXT` to pipe the output columns/variables of one GQL query stage into the
next stage (similar to a pipe operator), allowing per-stage aggregation and
filtering. `RETURN` must be the last statement of a stage, so filter on
aggregated columns at the start of the next stage:

```sql
GRAPH ECommerceGraph
MATCH (c:Customer)-[:PLACED]->(o:`Order`)
RETURN c, COUNT(o) AS order_count, SUM(o.total_usd) AS lifetime_spend
GROUP BY c

NEXT

FILTER order_count >= 5
MATCH (c:Customer)-[r:REVIEWED]->(p:Product)
WHERE r.rating >= 4
RETURN c.name, lifetime_spend, COUNT(p) AS high_rated_reviews
GROUP BY c.name, lifetime_spend
ORDER BY lifetime_spend DESC;
```

## 5. Inspecting Labels and Properties

- `LABELS(element_var)`: Returns an `ARRAY<STRING>` of labels attached to a node
  or edge variable.
- `PROPERTY_NAMES(element_var)`: Returns an `ARRAY<STRING>` of property names
  defined on the element.
- `TO_JSON(element_var)`: Serializes a graph node, edge, or path variable to
  `JSON`.

## 6. Combining GQL with SQL (`GRAPH_TABLE`)

To join Spanner Graph traversal results with standard SQL tables or subqueries,
wrap the GQL query inside `GRAPH_TABLE`:

```sql
SELECT gt.customer_id, gt.recommended_product, inv.stock_count
FROM GRAPH_TABLE(
  ECommerceGraph
  MATCH (c:Customer {customer_id: 42})-[:PLACED]->(:`Order`)-[:INCLUDES_ITEM]->(p:Product)
  RETURN c.customer_id, p.product_id, p.title AS recommended_product
) AS gt
JOIN Inventory AS inv ON gt.product_id = inv.product_id
WHERE inv.stock_count > 0;
```
patterns.md 12.9 KB
# Relational-to-Property-Graph Mapping Patterns

## Table of Contents

- [1. Entity vs. Junction Table Classification](#1-entity-vs-junction-table-classification):
  Lines 18-63
- [2. Interleaved Parent-Child Hierarchies and Foreign Keys](#2-interleaved-parent-child-hierarchies-and-foreign-keys):
  Lines 67-120
- [3. Self-Referential and Recursive Hierarchies](#3-self-referential-and-recursive-hierarchies):
  Lines 124-144
- [4. SQL Bridge Views for Implicit Relationships](#4-sql-bridge-views-for-implicit-relationships):
  Lines 148-208
- [5. Consolidated Multi-Typed and Polymorphic Entity Tables](#5-consolidated-multi-typed-and-polymorphic-entity-tables):
  Lines 212-232
- [6. Indexing and High-Degree Hub Node Recommendations](#6-indexing-and-high-degree-hub-node-recommendations):
  Lines 236-287

## 1. Entity vs. Junction Table Classification

### Pattern 1A: Core Entity Table (`NODE TABLE`)

- **Signals**: Has an independent single-column or composite primary key
  (`customer_id`, `account_id`, `(tenant_id, user_id)`), stores descriptive
  attributes, and is referenced by foreign keys or interleaved child tables.
- **Mapping**: Register in `NODE TABLES` with `KEY ({primary_key_columns})`.

### Pattern 1B: Pure M:N Junction Table (`EDGE TABLE` Only)

- **Signals**: Primary key is composed strictly of two foreign keys
  `(entity_a_id, entity_b_id)` (plus an optional timestamp or sequence number),
  and **no other table** references this table as a parent.
- **Mapping**: Register in `EDGE TABLES` only (`KEY (entity_a_id, entity_b_id)`,
  `SOURCE KEY (entity_a_id) REFERENCES EntityA(entity_a_id)`,
  `DESTINATION KEY (entity_b_id) REFERENCES EntityB(entity_b_id)`).

### Pattern 1C: Attributed Junction / Transaction Table (`EDGE TABLE` or Dual Node + Edge)

- **Signals**: Represents an event, transaction, or relationship with rich
  attributes (`WireTransfers`, `ProductReviews`, `ProjectAssignments`).
- **Mapping Decision**:
  - Map purely as an **`EDGE TABLE`** if no other table has a foreign key or
    interleave pointing to this table (for example, `WireTransfers` between two
    `BankAccounts`).
  - Map as **both a `NODE TABLE` and an `EDGE TABLE`** if downstream tables link
    to it (for example, `Orders` is linked from `Customers` and is the parent of
    `OrderItems`).

### Pattern 1D: Decoupled Edge Identity (`KEY`) vs. Endpoint Keys & Reverse Edge Aliasing

- **Edge Identity vs. Topology**: In Spanner Graph, `KEY (...)` identifies the
  unique edge row in the table (`KEY (transfer_id)` or
  `KEY (src_id, dst_id, transfer_id)`), whereas `SOURCE KEY` and
  `DESTINATION KEY` define the topological endpoints. `KEY` does not need to be
  identical to `(SOURCE KEY, DESTINATION KEY)`.
- **Reverse Edge Aliasing (Naming Only)**: A single physical edge table can be
  mapped twice in `EDGE TABLES` under distinct aliases (swapping `SOURCE KEY`
  and `DESTINATION KEY`, e.g., `AccountTransfers AS Debits` and
  `AccountTransfers AS Credits`) when the domain genuinely needs two directional
  labels. It is not a performance optimization: for undirected traversal use
  `-[e:LABEL]-` backed by a reverse index on `(dst_key, src_key)`; querying a
  swapped-key alias as a label union (`-[:E|E_REV]->{1,3}`) evaluates a union of
  two edge definitions at every hop, which is slower than `-[e:LABEL]-` for
  identical results.

---

## 2. Interleaved Parent-Child Hierarchies and Foreign Keys

### Pattern 2A: Interleaved Child Entity (`INTERLEAVE IN PARENT`)
In Spanner, parent-child ownership is frequently modeled via table interleaving
rather than an explicit `FOREIGN KEY` constraint:
```sql
CREATE TABLE Customers (
  customer_id INT64 NOT NULL,
  name STRING(100)
) PRIMARY KEY (customer_id);

CREATE TABLE Orders (
  customer_id INT64 NOT NULL,
  order_id INT64 NOT NULL,
  order_date DATE
) PRIMARY KEY (customer_id, order_id),
  INTERLEAVE IN PARENT Customers ON DELETE CASCADE;
```

- **Mapping**:
  - `Customers` -> `NODE TABLE` with `KEY (customer_id)`
  - `Orders` -> `NODE TABLE` (`Orders AS OrderNode`) with full composite
    `KEY (customer_id, order_id)`
  - `Orders` -> `EDGE TABLE` (`Orders AS PlacedOrder`) with:
    ```sql
    Orders AS PlacedOrder
      KEY (customer_id, order_id)
      SOURCE KEY (customer_id) REFERENCES Customer(customer_id)
      DESTINATION KEY (customer_id, order_id) REFERENCES OrderNode(customer_id, order_id)
      LABEL PLACED PROPERTIES (order_date)
    ```

- **Why**: Interleaving physically colocates `PlacedOrder` and `OrderNode` rows
  with their parent `Customer` split, making forward traversal
  `(c:Customer)-[:PLACED]->(o:Order)` a local split read. If queries or other
  edge tables look up `Orders` by `order_id` alone without `customer_id`,
  recommend `CREATE UNIQUE INDEX OrdersByOrderId ON Orders (order_id)` so those
  lookups do not full-scan `Orders` (and if downstream tables only carry
  `order_id`, either declare `KEY (order_id)` on `OrderNode` backed by that
  `UNIQUE` index or reference the full `(customer_id, order_id)` key).

### Pattern 2B: Standard 1:N Foreign Key (`Table AS Edge`)
When table `Accounts(account_id, owner_entity_id)` has a foreign key
`owner_entity_id REFERENCES Entities(entity_id)`:

- Register `Accounts AS Account` in `NODE TABLES` (`KEY (account_id)`).
- Register `Accounts AS OwnsAccountEdge` in `EDGE TABLES`:
  ```sql
  Accounts AS OwnsAccountEdge
    KEY (account_id)
    SOURCE KEY (owner_entity_id) REFERENCES Entity(entity_id)
    DESTINATION KEY (account_id) REFERENCES Account(account_id)
    LABEL OWNS NO PROPERTIES
  ```

---

## 3. Self-Referential and Recursive Hierarchies

When a table references its own primary key (for example,
`Employees(emp_id, manager_id)` or
`Categories(category_id, parent_category_id)`):

- Map the table once in `NODE TABLES` (`Employees AS Employee KEY (emp_id)`).
- Map the table again in `EDGE TABLES` with a distinct alias
  (`Employees AS ReportsToEdge`):
  ```sql
  Employees AS ReportsToEdge
    KEY (emp_id)
    SOURCE KEY (emp_id) REFERENCES Employee(emp_id)
    DESTINATION KEY (manager_id) REFERENCES Employee(emp_id)
    LABEL REPORTS_TO NO PROPERTIES
  ```

- Note: Rows where `manager_id IS NULL` (such as root/CEO nodes) remain valid
  nodes in `Employee`; Spanner Graph simply omits null-destination edges during
  edge traversal. By contrast, if a node or edge's own `KEY (...)` column is
  `NULL`, `MATCH` silently hides that element row altogether.

---

## 4. SQL Bridge Views for Implicit Relationships

Because existing relational tables should not be destructively altered, use SQL
bridge views whenever relationships are stored implicitly. Every Spanner view
requires a `SQL SECURITY` clause:

- **`SQL SECURITY INVOKER` (common default)**: Graph queries run with the
  invoking caller's permissions on the underlying relational tables.
- **`SQL SECURITY DEFINER`**: Use when enforcing row-level / fine-grained access
  control so callers can query the graph view without direct privileges on the
  base tables.

### Case 4A: Array of Foreign Keys (`ARRAY<INT64>` / `ARRAY<STRING>`)

If `Articles(article_id INT64, tag_ids ARRAY<INT64>)` stores foreign keys in an
array column, `ARRAY` columns cannot be used directly in `SOURCE KEY` or
`DESTINATION KEY`. Create an unnesting bridge view:

```sql
CREATE OR REPLACE VIEW ArticleTagEdgeView
SQL SECURITY INVOKER AS
SELECT DISTINCT
  a.article_id,
  tag_id
FROM Articles AS a,
UNNEST(a.tag_ids) AS tag_id
WHERE tag_id IS NOT NULL;
```

Then register `ArticleTagEdgeView` in `EDGE TABLES` with an explicit composite
`KEY (article_id, tag_id)`:

- **Strict key validation (default)**: Spanner verifies view element keys
  syntactically (either a single table's primary key or `SELECT DISTINCT` /
  `GROUP BY` over the key columns), failing otherwise with
  `cannot verify the specified element key (article_id, tag_id) is unique`. Keep
  `SELECT DISTINCT` (or `GROUP BY`) whenever raw array values can repeat.
- **Skipping syntactic validation
  (`OPTIONS (validate_element_key_uniqueness = false)`)**: When you know a
  view's `KEY` is **already semantically unique**—such as
  `UNNEST(a.tag_ids) AS tag_id WITH OFFSET AS pos` keyed on `(article_id, pos)`,
  or a `JOIN` that preserves primary-key uniqueness without `GROUP BY`—you can
  append `OPTIONS (validate_element_key_uniqueness = false)` to
  `CREATE PROPERTY GRAPH` instead of adding `DISTINCT` / `GROUP BY`. Ensure the
  key columns contain no duplicate rows in data, or `MATCH` can return duplicate
  graph elements.

### Case 4B: JSON Relationship Payloads

If foreign keys are nested inside a `JSON` column (`metadata.parent_device_id`),
project the scalar key in a bridge view (`SQL SECURITY INVOKER` or `DEFINER`)
using `INT64(JSON_QUERY(metadata, '$.parent_device_id'))` or
`JSON_VALUE(metadata, '$.parent_device_id')`.

### Case 4C: Mismatched Key Data Types (`INT64` vs. `STRING`)

If a legacy table stores `target_account_id` as `STRING(64)` while
`Accounts(account_id)` is `INT64`, create a bridge view (`SQL SECURITY INVOKER`
or `DEFINER`) using
`SAFE_CAST(target_account_id AS INT64) AS target_account_id_int64` and filter
`WHERE SAFE_CAST(target_account_id AS INT64) IS NOT NULL`.

---

## 5. Consolidated Multi-Typed and Polymorphic Entity Tables

Some schemas consolidate multiple domain types into a single table with a
composite primary key `(entity_type, entity_id)`:
```sql
CREATE TABLE Entities (
  entity_type STRING(50) NOT NULL,
  entity_id STRING(100) NOT NULL,
  display_name STRING(200)
) PRIMARY KEY (entity_type, entity_id);
```

- **Recommended Default Mapping**: Map `Entities` to a single unified node table
  (`Entities AS Entity` with `KEY (entity_type, entity_id)` and
  `LABEL Entity PROPERTIES (entity_type, entity_id, display_name)`) and match
  edges on the full 2-column key
  `(source_type, source_id) -> (target_type, target_id)`.
- **Optional Typed Subgraph Views**: If users require distinct node labels per
  type (`:Malware`, `:ThreatActor`), create `SQL SECURITY INVOKER` views
  filtered by `WHERE entity_type = '...'` and register each view as a separate
  node table.

---

## 6. Indexing and High-Degree Hub Node Recommendations

Always include physical performance recommendations alongside the derived
`CREATE PROPERTY GRAPH` DDL:

1. **Reverse Traversal Secondary Indexes (Remote Interleaved or Covering)**:
   - Every edge table whose primary key begins with `src_id` is fast for forward
     traversal (`(src)-[:EDGE]->(dst)`) but requires a full table scan for
     reverse traversal (`(dst)<-[:EDGE]-(src)`) unless indexed on `dst_id`.
   - Recommend either a **Remote Interleaved Index** co-located in the
     destination node table (`INTERLEAVE IN DestNodeTable`, which matches
     `dst_id` to `DestNodeTable`'s primary key positionally by type) or a
     covering index with `STORING`:
     ```sql
     -- Option A: Remote index physically co-located with the destination node table
     -- (if dst_id is nullable, use CREATE NULL_FILTERED INDEX because Spanner
     -- rejects non-NULL_FILTERED interleaved indexes on nullable columns)
     CREATE INDEX EdgeTableByDstSrc
     ON EdgeTable (dst_id, src_id),
     INTERLEAVE IN DestNodeTable;

     -- Option B: Global covering index storing frequently filtered edge properties
     CREATE INDEX EdgeTableByDstSrcCovering
     ON EdgeTable (dst_id, src_id)
     STORING (prop1, prop2);
     ```

2. **Simplify Over-Wide Composite Primary Keys on Junction Tables**:
   - Legacy relational junction tables sometimes include 4–6 status,
     source-system, or audit columns in the table `PRIMARY KEY`. Advise users
     that overly wide primary keys bloat secondary indexes and slow down edge
     joins; recommend keeping `PRIMARY KEY` to `(src_id, dst_id [, edge_id])`
     when evolving the physical schema.
3. **Interleaving vs. Bidirectional Cascading Deletes on Same-Node-Type Edges**:
   - When an edge connects two nodes of the same table (`Account -> Account`),
     explain the trade-off:
     - **Interleaving** (`INTERLEAVE IN PARENT Accounts`) maximizes forward
       traversal locality, OR
     - **Standalone table with two `FOREIGN KEY ... ON DELETE CASCADE`
       constraints** (one on `src_id`, one on `dst_id`) ensures deleting an
       account automatically deletes both its outgoing and incoming edges.
4. **High-Degree Hub Node Contention (`NOT ENFORCED` Foreign Keys)**:
   - In scale-free graphs where a single popular destination node receives
     thousands of concurrent edge inserts per second, enforced foreign keys can
     cause validation lock contention on the hub node row. Informational foreign
     keys (`FOREIGN KEY (...) REFERENCES ... NOT ENFORCED`) avoid that
     contention and still allow optimizer join elimination, but they don't
     prevent dangling edges, and because the optimizer uses them by default,
     queries can return results that don't match the data if an edge points to a
     missing node. Keep foreign keys enforced by default; recommend
     `NOT ENFORCED` only when write throughput on hub nodes is critical and the
     user confirms that the application can tolerate dangling edges.
spanner-graph-ddl-syntax.md 7.3 KB
# Spanner Property Graph DDL Syntax Reference

## Table of Contents

- [1. Formal Grammar (`CREATE PROPERTY GRAPH`)](#1-formal-grammar-create-property-graph):
  Lines 10-57
- [2. Syntax Rules and Clause Reference](#2-syntax-rules-and-clause-reference):
  Lines 61-152

## 1. Formal Grammar (`CREATE PROPERTY GRAPH`)

```sql
CREATE [ OR REPLACE ] PROPERTY GRAPH [ IF NOT EXISTS ] graph_name
  NODE TABLES (
    node_table_definition [, ...]
  )
  [ EDGE TABLES (
    edge_table_definition [, ...]
  ) ]
  [ OPTIONS (
    validate_element_key_uniqueness = { true | false } [, ...]
  ) ];
```

- **Strict Section Ordering**: `NODE TABLES (...)` must appear **before**
  `EDGE TABLES (...)`.

### `node_table_definition`
```sql
table_or_view_name [ AS node_table_alias ]
  [ KEY ( key_column_name [, ...] ) ]
  [ label_and_properties_list ]
  [ DYNAMIC LABEL ( label_column_name ) ]
  [ DYNAMIC PROPERTIES ( json_column_name ) ]
```

### `edge_table_definition`
```sql
table_or_view_name [ AS edge_table_alias ]
  [ KEY ( key_column_name [, ...] ) ]
  SOURCE KEY ( src_column_name [, ...] ) REFERENCES src_node_table_alias [ ( ref_column_name [, ...] ) ]
  DESTINATION KEY ( dst_column_name [, ...] ) REFERENCES dst_node_table_alias [ ( ref_column_name [, ...] ) ]
  [ label_and_properties_list ]
  [ DYNAMIC LABEL ( label_column_name ) ]
  [ DYNAMIC PROPERTIES ( json_column_name ) ]
```

### `label_and_properties_list`

```sql
{ DEFAULT LABEL | LABEL label_name }
  [ {
    NO PROPERTIES
    | PROPERTIES ( column_name [ AS property_name ] [, ...] )
    | PROPERTIES ALL COLUMNS [ EXCEPT ( column_name [, ...] ) ]
  } ]
```

---

## 2. Syntax Rules and Clause Reference

1. **`AS node_table_alias` / `AS edge_table_alias`**:
   - Every element definition has an element alias (defaults to
     `table_or_view_name` if `AS` is omitted).
   - **Global Uniqueness**: Every alias across both `NODE TABLES` and
     `EDGE TABLES` in the same property graph must be unique. When a relational
     table acts as both a node and an edge (or backs multiple edge types),
     assign distinct aliases (`Employees AS Employee`,
     `Employees AS ReportsToEdge`, `Employees AS MemberOfDeptEdge`).
2. **`KEY ( ... )`**:
   - Must uniquely identify each row in the backing table or view.
   - For base tables, always specify the full `PRIMARY KEY` column list in key
     order (including interleaved parent primary key columns).
   - For SQL bridge views (`SQL SECURITY INVOKER` or `SQL SECURITY DEFINER`,
     which lack a physical `PRIMARY KEY`), `KEY (...)` is **mandatory** and must
     specify a unique composite column tuple.
   - By default (`validate_element_key_uniqueness = true`), Spanner enforces
     uniqueness at DDL time: a table `KEY` must contain all primary key columns
     or match a `UNIQUE` index (`UNIQUE NULL_FILTERED` is accepted), and a view
     `KEY` must be syntactically provably unique (a single base table's primary
     key passed through unchanged, or `SELECT DISTINCT` / `GROUP BY` over the
     key columns). If a view's `KEY` is already semantically unique (for
     example, a PK-preserving `JOIN` without `GROUP BY`), you can disable
     syntactic view-key validation with
     `OPTIONS (validate_element_key_uniqueness = false)` on
     `CREATE PROPERTY GRAPH`—you must ensure the `KEY` columns are genuinely
     unique in data.
   - **Silent `NULL` Key Filtering**: DDL succeeds even if `KEY` columns are
     nullable, but any row where a node or edge `KEY` column (or an edge's
     `SOURCE KEY` / `DESTINATION KEY` column) is `NULL` is **silently skipped**
     by `MATCH` queries (so SQL `COUNT(*)` can exceed
     `MATCH (n) RETURN COUNT(n)`). Prefer `NOT NULL` key columns or filter
     `WHERE key_col IS NOT NULL` in views.
3. **`SOURCE KEY` and `DESTINATION KEY`**:
   - The identifier immediately following `REFERENCES` **must** match the
     **`node_table_alias`** declared in `NODE TABLES` (not the `LABEL` name and
     not the raw table name if an alias was used).
   - The number and data types of columns in `SOURCE KEY (...)` and
     `DESTINATION KEY (...)` must match the referenced node's `KEY (...)`
     1-to-1.
   - Always reference the **full** node key. If the `REFERENCES` column list is
     omitted, an arity mismatch is a compile error; but with an explicit list,
     Spanner accepts a partial key (for example,
     `REFERENCES OrderNode (order_id)` against `KEY (customer_id, order_id)`)
     and each edge then matches every node sharing that value.
4. **`LABEL`, `PROPERTIES`, `DYNAMIC LABEL`, and `DYNAMIC PROPERTIES`**:
   - On clean single-table labels without cross-table column type conflicts,
     omitting the `PROPERTIES` clause (implicit `PROPERTIES ALL COLUMNS`) is
     concise and idiomatic. Use explicit `PROPERTIES (col1 [AS alias], ...)`,
     `PROPERTIES ALL COLUMNS EXCEPT (...)`, or `NO PROPERTIES` when: (1)
     aliasing columns to resolve graph-wide property type conflicts across
     legacy tables, (2) matching identical property sets on a shared `LABEL`,
     (3) mapping dual `Table AS Node` + `Table AS Edge` or pure junction tables
     (`NO PROPERTIES` or edge-only properties), or (4) excluding
     internal/sensitive columns.
   - For schemaless tables that store runtime labels in a `STRING` column and
     dynamic attributes in a `JSON` column (a hybrid properties design), either
     use `PROPERTIES ALL COLUMNS EXCEPT (properties)` or list the static columns
     explicitly so the `JSON` column is not exposed twice:
     ```sql
     PROPERTIES (id, label, created_at)
     DYNAMIC LABEL (label)
     DYNAMIC PROPERTIES (properties)
     ```

   - Store `DYNAMIC LABEL` values in **lowercase**. A row whose label column
     holds an uppercase or mixed-case value (for example, `'Person'`) silently
     gets no dynamic label, so `MATCH (n:Person)` returns no rows for it. Labels
     in queries are case-insensitive (`:Person` matches a stored `'person'`).
     Enforce this with `CONSTRAINT label_lowercase CHECK (label = LOWER(label))`
     on the table.
   - Supported static property types include standard Spanner scalar types
     (`BOOL`, `INT64`, `FLOAT32`, `FLOAT64`, `NUMERIC`, `STRING`, `BYTES`,
     `DATE`, `TIMESTAMP`, `JSON`) and arrays of supported scalar types. (Spanner
     tables cannot contain `STRUCT` columns.)
   - A property name must have **one data type across the entire graph**, even
     under different labels or on node vs. edge tables. If two tables expose a
     same-named column with different types (for example, `id INT64` and
     `id STRING`), alias one side (`id AS user_id`) or `CAST` it; implicit
     `DEFAULT LABEL PROPERTIES ALL COLUMNS` hits this conflict too.
   - `PROPERTIES ALL COLUMNS` is expanded when the graph is created: columns
     added to the table later are not exposed until you re-run
     `CREATE OR REPLACE PROPERTY GRAPH`. Columns and tables referenced by a
     graph cannot be dropped or retyped until the graph stops referencing them.
5. **Reserved Keywords**:
   - Escape GQL / SQL reserved keywords used as identifiers or labels in
     backticks, or rename the alias/label to a non-reserved identifier
     (`OrderNode`). Verified to require escaping: `` `Order` ``, `` `Group` ``,
     `` `Contains` `` (unescaped they fail with
     `Syntax error: Unexpected keyword ...`). `User`, `Edge`, `Node`, `Path`,
     and `Graph` were accepted unescaped as aliases and labels.
structural-invariants.md 9.5 KB
# Spanner Graph DDL Structural Invariants & Compiler Error Prevention

## Table of Contents

- [1. Unique Element Table Aliases Across Nodes and Edges](#1-unique-element-table-aliases-across-nodes-and-edges):
  Lines 27-45
- [2. `REFERENCES` Must Target the Node Alias](#2-references-must-target-the-node-alias-never-the-label-or-unaliased-table-name):
  Lines 47-55
- [3. Shared Labels Must Have Identical Property Signatures](#3-shared-labels-must-have-identical-property-signatures):
  Lines 57-71
- [4. Reference the Full Node Key, With Matching Types](#4-reference-the-full-node-key-with-matching-types-source-key-and-destination-key):
  Lines 73-101
- [5. Explicit, Unique `KEY` Clause on SQL Bridge Views](#5-explicit-unique-key-clause-on-sql-bridge-views-or-validate_element_key_uniqueness):
  Lines 103-133
- [6. One Data Type per Property Name Across the Entire Graph](#6-one-data-type-per-property-name-across-the-entire-graph):
  Lines 135-152
- [7. Every View Needs a `SQL SECURITY` Clause](#7-every-view-needs-a-sql-security-clause-invoker-vs-definer):
  Lines 154-166
- [8. Custom `KEY` Clause on a Table Must Contain the Primary Key or Match a Unique Index](#8-custom-key-clause-on-a-table-must-contain-the-primary-key-or-match-a-unique-index-and-avoid-null-keys):
  Lines 168-186

Before outputting or applying a `CREATE PROPERTY GRAPH` DDL statement, verify
all 8 invariants below. The quoted messages are the actual Spanner errors
(verified against a live instance); where Spanner does **not** reject a mistake,
the invariant says so explicitly.

## 1. Unique Element Table Aliases Across Nodes and Edges

- **Compiler Error**:
  `The node table '{alias_name}' is defined more than once; use a unique name`
- **Cause**: Using the same relational table in `NODE TABLES` and `EDGE TABLES`
  (or multiple times in `EDGE TABLES`) without unique `AS {alias_name}` names.
- **Fix**: Assign a distinct `AS` alias to every node and edge entry:
  ```sql
  NODE TABLES (
    Accounts AS Account KEY (account_id) LABEL Account PROPERTIES (account_id, balance)
  )
  EDGE TABLES (
    Accounts AS AccountParentEdge
      KEY (account_id)
      SOURCE KEY (account_id) REFERENCES Account(account_id)
      DESTINATION KEY (parent_account_id) REFERENCES Account(account_id)
      LABEL HAS_PARENT NO PROPERTIES
  )
  ```

## 2. `REFERENCES` Must Target the Node Alias (Never the Label or Unaliased Table Name)

- **Compiler Error**:
  `The referenced node table '{name}' is not defined in the property graph`
- **Cause**: Writing `REFERENCES Accounts(account_id)` when the node table was
  aliased as `Accounts AS Account`, or referencing the `LABEL` name when it
  differs from the `AS` alias.
- **Fix**: Ensure every `REFERENCES {node_alias}(...)` in `EDGE TABLES` matches
  the exact `AS {node_alias}` declared in `NODE TABLES`.

## 3. Shared Labels Must Have Identical Property Signatures

- **Compiler Error**:

  ```text
  The label '{label_name}' is defined with different properties. One definition of the label has 2 property declarations: '[id, code]'. Another definition has 1 property declarations: '[id]'. You need to use the same set of property declarations under the same label
  ```

- **Cause**: Two node or edge definitions share a `LABEL` (for example,
  `LABEL Entity` or `LABEL CONNECTED_TO`) and use `PROPERTIES ALL COLUMNS` on
  tables that have different columns, or declare different property sets.
- **Fix**: Either assign distinct labels to each table (`LABEL Customer`,
  `LABEL Vendor`) or explicitly list the exact common subset of properties
  (`LABEL Entity PROPERTIES (id, name, created_at)`) using column aliases
  (`col_a AS name`) so names and types match 100%.

## 4. Reference the Full Node Key, With Matching Types (`SOURCE KEY` and `DESTINATION KEY`)

- **Compiler Errors**:
  - Arity (only when the `REFERENCES` column list is omitted):

    ```text
    The number of referencing columns in the edge table does not match that of referenced columns in the node table; the former has a size of 1 but the latter has a size of 2
    ```

  - Types:

    ```text
    Data types and/or annotations of the referencing columns in the edge table do not match those of the referenced columns in the node table
    ```

- **Silent failure (no error)**: With an explicit column list, Spanner
  **accepts** a reference to a *subset* of a composite node key, for example
  `DESTINATION KEY (order_id) REFERENCES OrderNode (order_id)` where `OrderNode`
  has `KEY (customer_id, order_id)`. Each edge row then matches **every** node
  that shares that `order_id` value, so traversals return duplicated or wrong
  results.
- **Fix**:
  - Always include all composite key columns of the referenced node in
    `SOURCE KEY` / `DESTINATION KEY` and its `REFERENCES` list (for interleaved
    child nodes, that includes the parent key columns).
  - If two tables join across mismatched data types (`INT64` vs. `STRING`),
    create a SQL bridge view (`SQL SECURITY INVOKER` or `DEFINER`) that casts
    the column (`SAFE_CAST(target_id AS INT64) AS target_id_int64`) and bind the
    edge table to the view.

## 5. Explicit, Unique `KEY` Clause on SQL Bridge Views (or `validate_element_key_uniqueness`)

- **Compiler Errors**:
  - Missing key:

    ```text
    The node table '{view_name}' does not have primary key defined; graph element table keys must be explicitly defined
    ```

  - Unverifiable key (under default strict validation):

    ```text
    failed to create the graph element '{view_name}' based on view '{view_name}', because we cannot verify the specified element key (...) is unique
    ```

- **Cause**: SQL views have no physical `PRIMARY KEY`, and by default
  (`validate_element_key_uniqueness = true`) Spanner syntactically checks that
  the declared view `KEY` comes from a single table's primary key or a
  `SELECT DISTINCT` / `GROUP BY` over the key columns. A plain `UNNEST` or
  `JOIN` view without `DISTINCT` / `GROUP BY` cannot be syntactically verified.
- **Fix**: Always declare an explicit `KEY (col1, col2, ...)` on view-backed
  elements, and either:
  1. Make the view syntactically unique (pass through a single table's primary
     key unchanged, or use `SELECT DISTINCT` / `GROUP BY` over the key
     columns—required whenever raw inputs like an `ARRAY` can actually contain
     duplicate values), **or**
  2. When you have verified that the view's `KEY` is **already semantically
     unique** (such as a PK-preserving `JOIN` or `UNNEST(...) WITH OFFSET`), set
     `OPTIONS (validate_element_key_uniqueness = false)` on
     `CREATE PROPERTY GRAPH` to skip syntactic validation (ensuring no duplicate
     keys exist in data).

## 6. One Data Type per Property Name Across the Entire Graph

- **Compiler Error**:

  ```text
  The property declaration of 'id' has type conflicts. There is an existing declaration of type STRING. There is a conflicting one of type INT64
  ```

- **Cause**: The same property name is exposed with different data types
  anywhere in the graph, even under *different* labels or on a node table vs. an
  edge table (for example, `Accounts.id INT64` and `Users.id STRING`). Omitting
  `PROPERTIES` (implicit `DEFAULT LABEL PROPERTIES ALL COLUMNS`) triggers it
  whenever legacy relational tables reuse generic column names (`id`, `status`,
  `type`, `created_at`) with different types.
- **Fix**: Rename one side with an alias (`id AS user_id`), exclude it
  (`PROPERTIES ALL COLUMNS EXCEPT (id)`), or `CAST` it to the common type in
  `PROPERTIES (...)`. (Spanner tables cannot contain `STRUCT` columns, so
  struct-typed properties only arise from views.)

## 7. Every View Needs a `SQL SECURITY` Clause (`INVOKER` vs. `DEFINER`)

- **DDL Error** (raised by `CREATE VIEW`, not by the graph):
  `View '{view_name}' is missing the SQL SECURITY clause.`
- **Behavior**: `CREATE PROPERTY GRAPH` supports views defined with either
  `SQL SECURITY INVOKER` or `SQL SECURITY DEFINER`.
- **Fix**: Always include an explicit `SQL SECURITY` clause on
  `CREATE [OR REPLACE] VIEW`:
  - **`SQL SECURITY INVOKER`** (common default): Evaluates the view using the
    invoking caller's permissions on the underlying relational tables.
  - **`SQL SECURITY DEFINER`**: Evaluates the view with definer's rights—use
    when implementing row-level / fine-grained access control so users can query
    the graph view without direct privileges on the base tables.

## 8. Custom `KEY` Clause on a Table Must Contain the Primary Key or Match a Unique Index (and Avoid `NULL` Keys)

- **Compiler Error**:

  ```text
  Neither the primary keys nor any unique index defined on the property graph element source table '{table}' provides the uniqueness guarantee for graph element '{alias}' belonging to the graph '{graph}'. You want to redefine the element key columns (...) based on the source table's primary keys, or create a unique index on the element's key columns.
  ```

- **Cause**: An explicit `KEY (...)` on a table-backed node or edge that is not
  a superset of the table's primary key and has no matching `UNIQUE` index. This
  also applies to edge keys such as `KEY (src_id, dst_id, transfer_ts)` on a
  table whose primary key is `transfer_id`.
- **Silent failure (`NULL` keys)**: If a node or edge `KEY` column (from a
  nullable primary key or a `UNIQUE NULL_FILTERED` index) contains `NULL`,
  `CREATE PROPERTY GRAPH` succeeds, but `MATCH` silently skips those rows.
- **Fix**: Use the table's primary key (or a superset of it) as the element
  `KEY`, or create a `UNIQUE` index on the key columns (`UNIQUE NULL_FILTERED`
  indexes are accepted), and ensure element `KEY` columns are `NOT NULL` (or
  filtered with `IS NOT NULL` in a view).
synthesized-conversions.md 19.8 KB
# Synthesized Relational to Spanner Property Graph Conversions

## Table of Contents

- [Example 1: Multi-Tier E-Commerce Platform](#example-1-multi-tier-e-commerce-platform):
  Lines 16-162
- [Example 2: Financial AML and Transaction Network](#example-2-financial-aml-and-transaction-network):
  Lines 166-280
- [Example 3: Enterprise Organization and Project Matrix](#example-3-enterprise-organization-and-project-matrix):
  Lines 284-410
- [Example 4: Consolidated Multi-Typed Entity Schema](#example-4-consolidated-multi-typed-entity-schema):
  Lines 414-514

---

## Example 1: Multi-Tier E-Commerce Platform

### User Request (Relational Schema Input)

```sql
CREATE TABLE Customers (
  customer_id INT64 NOT NULL,
  name        STRING(100) NOT NULL,
  email       STRING(100) NOT NULL,
  country     STRING(2),
) PRIMARY KEY (customer_id);

CREATE TABLE Orders (
  customer_id INT64 NOT NULL,
  order_id    INT64 NOT NULL,
  order_date  DATE NOT NULL,
  status      STRING(20) NOT NULL,
  total_usd   NUMERIC NOT NULL,
) PRIMARY KEY (customer_id, order_id),
  INTERLEAVE IN PARENT Customers ON DELETE CASCADE;

CREATE TABLE Products (
  product_id  INT64 NOT NULL,
  sku         STRING(50) NOT NULL,
  title       STRING(200) NOT NULL,
  price       NUMERIC NOT NULL,
) PRIMARY KEY (product_id);

CREATE TABLE OrderItems (
  customer_id INT64 NOT NULL,
  order_id    INT64 NOT NULL,
  item_id     INT64 NOT NULL,
  product_id  INT64 NOT NULL,
  quantity    INT64 NOT NULL,
  unit_price  NUMERIC NOT NULL,
  CONSTRAINT FK_OrderItem_Product FOREIGN KEY (product_id) REFERENCES Products (product_id)
) PRIMARY KEY (customer_id, order_id, item_id),
  INTERLEAVE IN PARENT Orders ON DELETE CASCADE;

CREATE TABLE ProductReviews (
  review_id   INT64 NOT NULL,
  customer_id INT64 NOT NULL,
  product_id  INT64 NOT NULL,
  rating      INT64 NOT NULL,
  review_text STRING(MAX),
  review_date TIMESTAMP NOT NULL,
  CONSTRAINT FK_Review_Customer FOREIGN KEY (customer_id) REFERENCES Customers (customer_id),
  CONSTRAINT FK_Review_Product FOREIGN KEY (product_id) REFERENCES Products (product_id)
) PRIMARY KEY (review_id);
```

### 1. Graph Extension Summary & Mapping

- **Domain Decomposition & Business Purpose**: Models the e-commerce purchase
  pipeline—customers, orders, products, line items, and reviews—to enable
  recommendation and co-purchasing traversals.
- **Target Graph Scoping Decision**: 1 Unified Property Graph
  (`ECommerceGraph`).

| Relational Table | Target Graph | Graph Role | Element Alias | Graph Label | Source -> Destination | Element Key | Domain Rationale |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| `Customers` | `ECommerceGraph` | Node Table | `Customer` | `Customer` | N/A | `(customer_id)` | Core entity |
| `Orders` | `ECommerceGraph` | Node Table | `OrderNode` | `Order` | N/A | `(customer_id, order_id)` | Core order entity |
| `Orders` | `ECommerceGraph` | Edge Table | `PlacedOrder` | `PLACED` | `Customer -> OrderNode` | `(customer_id, order_id)` | Interleaved parent-child ownership |
| `Products` | `ECommerceGraph` | Node Table | `Product` | `Product` | N/A | `(product_id)` | Core catalog entity |
| `OrderItems` | `ECommerceGraph` | Edge Table | `ContainsProduct` | `INCLUDES_ITEM` | `OrderNode -> Product` | `(customer_id, order_id, item_id)` | Interleaved line-item relationship |
| `ProductReviews` | `ECommerceGraph` | Edge Table | `ReviewedProduct` | `REVIEWED` | `Customer -> Product` | `(review_id)` | Attributed customer-product interaction |

- **Excluded Tables**: 0 tables excluded (all 5 tables mapped).

### 2. Derived Spanner Property Graph DDL

```sql
CREATE OR REPLACE PROPERTY GRAPH ECommerceGraph
  NODE TABLES (
    Customers AS Customer
      KEY (customer_id)
      LABEL Customer PROPERTIES (customer_id, name, email, country),
    Orders AS OrderNode
      KEY (customer_id, order_id)
      LABEL `Order` PROPERTIES (customer_id, order_id, order_date, status, total_usd),
    Products AS Product
      KEY (product_id)
      LABEL Product PROPERTIES (product_id, sku, title, price)
  )
  EDGE TABLES (
    Orders AS PlacedOrder
      KEY (customer_id, order_id)
      SOURCE KEY (customer_id) REFERENCES Customer(customer_id)
      DESTINATION KEY (customer_id, order_id) REFERENCES OrderNode(customer_id, order_id)
      LABEL PLACED PROPERTIES (order_date, total_usd),
    OrderItems AS ContainsProduct
      KEY (customer_id, order_id, item_id)
      SOURCE KEY (customer_id, order_id) REFERENCES OrderNode(customer_id, order_id)
      DESTINATION KEY (product_id) REFERENCES Product(product_id)
      LABEL INCLUDES_ITEM PROPERTIES (quantity, unit_price),
    ProductReviews AS ReviewedProduct
      KEY (review_id)
      SOURCE KEY (customer_id) REFERENCES Customer(customer_id)
      DESTINATION KEY (product_id) REFERENCES Product(product_id)
      LABEL REVIEWED PROPERTIES (rating, review_text, review_date)
  );
```

### 3. Performance & Indexing Recommendations

1. **Forward Traversal Colocation**: `Orders` is interleaved in `Customers` and
   `OrderItems` is interleaved in `Orders`, colocating
   `Customer -> Order -> INCLUDES_ITEM` on the same split.
2. **Reverse Traversal Indexes**: To traverse inbound from `Product`
   (`(p:Product)<-[:INCLUDES_ITEM]-(o:Order)` or
   `(p:Product)<-[:REVIEWED]-(c:Customer)`), add covering secondary indexes:
   ```sql
   CREATE INDEX OrderItemsByProduct
   ON OrderItems (product_id, customer_id, order_id)
   STORING (quantity, unit_price);

   CREATE INDEX ReviewsByProduct
   ON ProductReviews (product_id, customer_id)
   STORING (rating, review_date);
   ```

### 4. Sample ISO GQL Queries

```sql
-- 1. Find customers who reviewed products they ordered with rating >= 4:
GRAPH ECommerceGraph
MATCH (c:Customer)-[:PLACED]->(o:`Order`)-[:INCLUDES_ITEM]->(p:Product)<-[r:REVIEWED]-(c)
WHERE r.rating >= 4 AND o.total_usd > 200
RETURN c.name AS customer_name, p.title AS product_title, r.rating, o.total_usd;

-- 2. Frequently bought together co-occurrence recommendation:
GRAPH ECommerceGraph
MATCH (p1:Product {product_id: 101})<-[:INCLUDES_ITEM]-(o:`Order`)-[:INCLUDES_ITEM]->(p2:Product)
WHERE p2.product_id != 101
RETURN p2.title AS recommended_product, COUNT(o) AS co_occurrence_count
GROUP BY p2.title
ORDER BY co_occurrence_count DESC
LIMIT 5;
```

### 5. Schema Verification Status

- **Verification Target**: Spanner Emulator
  (`gcloud spanner databases create --ddl-file=...`)
- **Status**: `PASSED` (Composite keys on interleaved `Orders` and `OrderItems`
  aligned; reserved identifier `` `Order` `` escaped).

---

## Example 2: Financial AML and Transaction Network

### User Request (Relational Schema Input)

```sql
CREATE TABLE FinancialEntities (
  entity_id    INT64 NOT NULL,
  entity_type  STRING(30) NOT NULL,
  legal_name   STRING(150) NOT NULL,
  jurisdiction STRING(50),
) PRIMARY KEY (entity_id);

CREATE TABLE BankAccounts (
  account_id  INT64 NOT NULL,
  entity_id   INT64 NOT NULL,
  iban        STRING(34) NOT NULL,
  currency    STRING(3) NOT NULL,
  balance     NUMERIC NOT NULL,
  is_flagged  BOOL NOT NULL,
  CONSTRAINT FK_Account_Entity FOREIGN KEY (entity_id) REFERENCES FinancialEntities (entity_id)
) PRIMARY KEY (account_id);

CREATE TABLE WireTransfers (
  transfer_id    INT64 NOT NULL,
  src_account_id INT64 NOT NULL,
  dst_account_id INT64 NOT NULL,
  amount         NUMERIC NOT NULL,
  transfer_time  TIMESTAMP NOT NULL,
  audit_score    FLOAT64,
  CONSTRAINT FK_Transfer_Src FOREIGN KEY (src_account_id) REFERENCES BankAccounts (account_id),
  CONSTRAINT FK_Transfer_Dst FOREIGN KEY (dst_account_id) REFERENCES BankAccounts (account_id)
) PRIMARY KEY (transfer_id);
```

### 1. Graph Extension Summary & Mapping

- **Domain Decomposition & Business Purpose**: Models financial entities, bank
  accounts, and wire transfers for anti-money laundering (AML) cycle detection
  and multi-hop fund tracing.
- **Target Graph Scoping Decision**: 1 Unified Property Graph (`FinCrimeGraph`).

| Relational Table | Target Graph | Graph Role | Element Alias | Graph Label | Source -> Destination | Element Key | Domain Rationale |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| `FinancialEntities` | `FinCrimeGraph` | Node Table | `Entity` | `Entity` | N/A | `(entity_id)` | Core legal entity |
| `BankAccounts` | `FinCrimeGraph` | Node Table | `Account` | `Account` | N/A | `(account_id)` | Core account node |
| `BankAccounts` | `FinCrimeGraph` | Edge Table | `EntityOwnsAccount` | `OWNS` | `Entity -> Account` | `(account_id)` | 1:N ownership via FK |
| `WireTransfers` | `FinCrimeGraph` | Edge Table | `AccountTransfers` | `TRANSFERRED_TO` | `Account -> Account` | `(transfer_id)` | Directed transaction edge |

- **Excluded Tables**: 0 tables excluded.

### 2. Derived Spanner Property Graph DDL

```sql
CREATE OR REPLACE PROPERTY GRAPH FinCrimeGraph
  NODE TABLES (
    FinancialEntities AS Entity
      KEY (entity_id)
      LABEL Entity PROPERTIES (entity_id, entity_type, legal_name, jurisdiction),
    BankAccounts AS Account
      KEY (account_id)
      LABEL Account PROPERTIES (account_id, iban, currency, balance, is_flagged)
  )
  EDGE TABLES (
    BankAccounts AS EntityOwnsAccount
      KEY (account_id)
      SOURCE KEY (entity_id) REFERENCES Entity(entity_id)
      DESTINATION KEY (account_id) REFERENCES Account(account_id)
      LABEL OWNS NO PROPERTIES,
    WireTransfers AS AccountTransfers
      KEY (transfer_id)
      SOURCE KEY (src_account_id) REFERENCES Account(account_id)
      DESTINATION KEY (dst_account_id) REFERENCES Account(account_id)
      LABEL TRANSFERRED_TO PROPERTIES (amount, transfer_time, audit_score)
  );
```

### 3. Performance & Indexing Recommendations

1. **Outbound and Inbound Transfer Indexes**: Because `WireTransfers` uses a
   synthetic single-column key `(transfer_id)`, add secondary indexes for both
   forward (`src_account_id`) and reverse (`dst_account_id`) traversals:
   ```sql
   CREATE INDEX WireTransfersBySrcDst
   ON WireTransfers (src_account_id, dst_account_id, transfer_time)
   STORING (amount, audit_score);

   CREATE INDEX WireTransfersByDstSrc
   ON WireTransfers (dst_account_id, src_account_id, transfer_time)
   STORING (amount, audit_score);
   ```

2. **Same-Node-Type Edge Trade-Off**: Keeping `WireTransfers` as a standalone
   table allows bidirectional `ON DELETE CASCADE` foreign keys on both
   `src_account_id` and `dst_account_id` so deleting an account cleans up both
   incoming and outgoing transfers.

### 4. Sample ISO GQL Queries

```sql
-- 1. Detect circular funds routing (cycles of 2 to 4 hops):
GRAPH FinCrimeGraph
MATCH (a:Account {account_id: @acct_id})-[t:TRANSFERRED_TO]->{2, 4}(a:Account)
RETURN a.iban AS account_iban, ARRAY_LENGTH(t) AS cycle_depth;

-- 2. Trace funds from high-risk jurisdictions to flagged accounts:
GRAPH FinCrimeGraph
MATCH (e:Entity)-[:OWNS]->(src:Account)-[t:TRANSFERRED_TO]->{1, 3}(dst:Account)
WHERE e.jurisdiction IN ('HIGH_RISK_A', 'HIGH_RISK_B') AND dst.is_flagged = TRUE
RETURN e.legal_name, src.iban AS src_iban, dst.iban AS dst_iban, ARRAY_LENGTH(t) AS hops;
```

### 5. Schema Verification Status

- **Verification Target**: Spanner Emulator
- **Status**: `PASSED`

---

## Example 3: Enterprise Organization and Project Matrix

### User Request (Relational Schema Input)

```sql
CREATE TABLE Departments (
  dept_id     INT64 NOT NULL,
  dept_name   STRING(100) NOT NULL,
  cost_center STRING(20),
) PRIMARY KEY (dept_id);

CREATE TABLE Employees (
  emp_id     INT64 NOT NULL,
  full_name  STRING(100) NOT NULL,
  job_title  STRING(100) NOT NULL,
  dept_id    INT64 NOT NULL,
  manager_id INT64,
  CONSTRAINT FK_Emp_Dept FOREIGN KEY (dept_id) REFERENCES Departments (dept_id),
  CONSTRAINT FK_Emp_Mgr FOREIGN KEY (manager_id) REFERENCES Employees (emp_id)
) PRIMARY KEY (emp_id);

CREATE TABLE Projects (
  project_id   INT64 NOT NULL,
  project_code STRING(50) NOT NULL,
  budget       NUMERIC,
) PRIMARY KEY (project_id);

CREATE TABLE ProjectAssignments (
  emp_id     INT64 NOT NULL,
  project_id INT64 NOT NULL,
  role_name  STRING(50) NOT NULL,
  allocation NUMERIC NOT NULL,
  CONSTRAINT FK_Assign_Emp FOREIGN KEY (emp_id) REFERENCES Employees (emp_id),
  CONSTRAINT FK_Assign_Proj FOREIGN KEY (project_id) REFERENCES Projects (project_id)
) PRIMARY KEY (emp_id, project_id);
```

### 1. Graph Extension Summary & Mapping

- **Domain Decomposition & Business Purpose**: Models organizational reporting
  hierarchies, department membership, and M:N project staffing.
- **Target Graph Scoping Decision**: 1 Unified Property Graph
  (`EnterpriseOrgGraph`).

| Relational Table | Target Graph | Graph Role | Element Alias | Graph Label | Source -> Destination | Element Key | Domain Rationale |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| `Departments` | `EnterpriseOrgGraph` | Node Table | `Department` | `Department` | N/A | `(dept_id)` | Core org unit |
| `Employees` | `EnterpriseOrgGraph` | Node Table | `Employee` | `Employee` | N/A | `(emp_id)` | Core person entity |
| `Projects` | `EnterpriseOrgGraph` | Node Table | `Project` | `Project` | N/A | `(project_id)` | Core workstream |
| `Employees` | `EnterpriseOrgGraph` | Edge Table | `ReportsToEdge` | `REPORTS_TO` | `Employee -> Employee` | `(emp_id)` | Self-referential hierarchy |
| `Employees` | `EnterpriseOrgGraph` | Edge Table | `MemberOfDeptEdge` | `MEMBER_OF` | `Employee -> Department` | `(emp_id)` | 1:N department membership |
| `ProjectAssignments` | `EnterpriseOrgGraph` | Edge Table | `AssignedToProject` | `ASSIGNED_TO` | `Employee -> Project` | `(emp_id, project_id)` | Attributed M:N junction |

- **Excluded Tables**: 0 tables excluded.

### 2. Derived Spanner Property Graph DDL

```sql
CREATE OR REPLACE PROPERTY GRAPH EnterpriseOrgGraph
  NODE TABLES (
    Departments AS Department
      KEY (dept_id)
      LABEL Department PROPERTIES (dept_id, dept_name, cost_center),
    Employees AS Employee
      KEY (emp_id)
      LABEL Employee PROPERTIES (emp_id, full_name, job_title),
    Projects AS Project
      KEY (project_id)
      LABEL Project PROPERTIES (project_id, project_code, budget)
  )
  EDGE TABLES (
    Employees AS ReportsToEdge
      KEY (emp_id)
      SOURCE KEY (emp_id) REFERENCES Employee(emp_id)
      DESTINATION KEY (manager_id) REFERENCES Employee(emp_id)
      LABEL REPORTS_TO NO PROPERTIES,
    Employees AS MemberOfDeptEdge
      KEY (emp_id)
      SOURCE KEY (emp_id) REFERENCES Employee(emp_id)
      DESTINATION KEY (dept_id) REFERENCES Department(dept_id)
      LABEL MEMBER_OF NO PROPERTIES,
    ProjectAssignments AS AssignedToProject
      KEY (emp_id, project_id)
      SOURCE KEY (emp_id) REFERENCES Employee(emp_id)
      DESTINATION KEY (project_id) REFERENCES Project(project_id)
      LABEL ASSIGNED_TO PROPERTIES (role_name, allocation)
  );
```

### 3. Performance & Indexing Recommendations

1. **Reverse Staffing Lookup Index**: To find all employees assigned to a given
   project (`(p:Project)<-[:ASSIGNED_TO]-(e:Employee)`):
   ```sql
   CREATE INDEX StaffingByProject
   ON ProjectAssignments (project_id, emp_id)
   STORING (role_name, allocation);
   ```

2. **Direct-Reports Lookup Index**: To traverse downward from a manager to
   direct reports (`(mgr:Employee)<-[:REPORTS_TO]-(report:Employee)`):
   ```sql
   CREATE INDEX EmployeesByManager
   ON Employees (manager_id, emp_id)
   STORING (full_name, job_title);
   ```

### 4. Sample ISO GQL Queries

```sql
-- 1. Traverse management chain up to 5 levels deep:
GRAPH EnterpriseOrgGraph
MATCH (e:Employee)-[r:REPORTS_TO]->{1, 5}(mgr:Employee)
WHERE mgr.job_title = 'VP of Engineering'
RETURN e.full_name AS employee_name, mgr.full_name AS executive_name, ARRAY_LENGTH(r) AS depth;

-- 2. Find cross-department project collaborations:
GRAPH EnterpriseOrgGraph
MATCH (d1:Department)<-[:MEMBER_OF]-(e1:Employee)-[:ASSIGNED_TO]->(p:Project)<-[:ASSIGNED_TO]-(e2:Employee)-[:MEMBER_OF]->(d2:Department)
WHERE d1.dept_id < d2.dept_id
RETURN p.project_code, d1.dept_name AS dept_1, e1.full_name AS emp_1, d2.dept_name AS dept_2, e2.full_name AS emp_2;
```

### 5. Schema Verification Status

- **Verification Target**: Spanner Emulator
- **Status**: `PASSED`

---

## Example 4: Consolidated Multi-Typed Entity Schema

### User Request (Relational Schema Input)

```sql
CREATE TABLE Entities (
  entity_type      STRING(50) NOT NULL,
  entity_id        STRING(100) NOT NULL,
  display_name     STRING(200),
  confidence_score FLOAT64,
  created_at       TIMESTAMP
) PRIMARY KEY (entity_type, entity_id);

CREATE TABLE EntityAssociations (
  source_type   STRING(50) NOT NULL,
  source_id     STRING(100) NOT NULL,
  target_type   STRING(50) NOT NULL,
  target_id     STRING(100) NOT NULL,
  relation_verb STRING(50) NOT NULL,
  first_seen    TIMESTAMP,
  CONSTRAINT FK_Source FOREIGN KEY (source_type, source_id) REFERENCES Entities (entity_type, entity_id),
  CONSTRAINT FK_Target FOREIGN KEY (target_type, target_id) REFERENCES Entities (entity_type, entity_id)
) PRIMARY KEY (source_type, source_id, target_type, target_id, relation_verb);

CREATE TABLE Labels (
  label_id STRING(50) NOT NULL,
  category STRING(50)
) PRIMARY KEY (label_id);

CREATE TABLE EntityLabels (
  entity_type STRING(50) NOT NULL,
  entity_id   STRING(100) NOT NULL,
  label_id    STRING(50) NOT NULL,
  CONSTRAINT FK_Entity FOREIGN KEY (entity_type, entity_id) REFERENCES Entities (entity_type, entity_id),
  CONSTRAINT FK_Label FOREIGN KEY (label_id) REFERENCES Labels (label_id)
) PRIMARY KEY (entity_type, entity_id, label_id);
```

### 1. Graph Extension Summary & Mapping

- **Consolidated Entity Strategy**: Maps the composite-keyed
  `Entities(entity_type, entity_id)` table to a unified `Entity` node table with
  `entity_type` exposed as a filterable property.

| Relational Table | Target Graph | Graph Role | Element Alias | Graph Label | Source -> Destination | Element Key |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| `Entities` | `ThreatIntelGraph` | Node Table | `Entity` | `Entity` | N/A | `(entity_type, entity_id)` |
| `Labels` | `ThreatIntelGraph` | Node Table | `LabelNode` | `Label` | N/A | `(label_id)` |
| `EntityAssociations` | `ThreatIntelGraph` | Edge Table | `AssociatedWithEdge` | `ASSOCIATED_WITH` | `Entity -> Entity` | `(source_type, source_id, target_type, target_id, relation_verb)` |
| `EntityLabels` | `ThreatIntelGraph` | Edge Table | `HasLabelEdge` | `HAS_LABEL` | `Entity -> LabelNode` | `(entity_type, entity_id, label_id)` |

### 2. Derived Spanner Property Graph DDL

```sql
CREATE OR REPLACE PROPERTY GRAPH ThreatIntelGraph
  NODE TABLES (
    Entities AS Entity
      KEY (entity_type, entity_id)
      LABEL Entity PROPERTIES (entity_type, entity_id, display_name, confidence_score, created_at),
    Labels AS LabelNode
      KEY (label_id)
      LABEL Label PROPERTIES (label_id, category)
  )
  EDGE TABLES (
    EntityAssociations AS AssociatedWithEdge
      KEY (source_type, source_id, target_type, target_id, relation_verb)
      SOURCE KEY (source_type, source_id) REFERENCES Entity(entity_type, entity_id)
      DESTINATION KEY (target_type, target_id) REFERENCES Entity(entity_type, entity_id)
      LABEL ASSOCIATED_WITH PROPERTIES (relation_verb, first_seen),
    EntityLabels AS HasLabelEdge
      KEY (entity_type, entity_id, label_id)
      SOURCE KEY (entity_type, entity_id) REFERENCES Entity(entity_type, entity_id)
      DESTINATION KEY (label_id) REFERENCES LabelNode(label_id)
      LABEL HAS_LABEL NO PROPERTIES
  );
```

### 3. Performance & Indexing Recommendations

```sql
CREATE INDEX IdxEntityAssocReverse
ON EntityAssociations (target_type, target_id, source_type, source_id, relation_verb)
STORING (first_seen);

CREATE INDEX IdxEntityLabelsReverse
ON EntityLabels (label_id, entity_type, entity_id);
```

### 4. Sample ISO GQL Queries

```sql
GRAPH ThreatIntelGraph
MATCH (m1:Entity {entity_type: 'MALWARE'})-[:ASSOCIATED_WITH]->(infra:Entity)<-[:ASSOCIATED_WITH]-(m2:Entity {entity_type: 'MALWARE'})
WHERE m1.entity_id < m2.entity_id
RETURN m1.display_name AS malware_1, m2.display_name AS malware_2, infra.display_name AS shared_c2;
```

### 5. Schema Verification Status

- **Verification Target**: Spanner Emulator
- **Status**: `PASSED`

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE