Spanner Relational to Graph Conversion

Spanner Relational to Graph Conversion

Analyses existing Spanner relational schemas and writes CREATE PROPERTY GRAPH DDL, mapping tables to nodes and edges without altering the underlying tables.

Skill files8 files

references/

SKILL.md299 lines
1
---
2
name: spanner-relational-to-graph
3
metadata:
4
version: "1.0.0"
5
category: Databases
6
description: >-
7
Analyzes existing Spanner relational schemas on Google Cloud (DDL, foreign
8
keys, interleaved tables, and junction tables) and generates
9
`CREATE PROPERTY GRAPH` DDL statements (`NODE TABLES`, `EDGE TABLES`) without
10
modifying underlying relational tables. Use when mapping existing Spanner
11
tables to a Spanner Graph, identifying node and edge candidates from
12
relational tables, creating SQL bridge views for implicit `ARRAY`/`JSON` or
13
type-mismatched relationships, mapping polymorphic or self-referential tables,
14
or troubleshooting `CREATE PROPERTY GRAPH` DDL compiler errors. Don't use for
15
greenfield physical table design (use spanner-graph-schema-best-practices) or
16
tuning slow ISO GQL queries (use spanner-graph-query-tuning).
17
---
18
19
# Spanner Relational-to-Property-Graph Schema Conversion
20
21
Convert an existing Spanner relational schema into a valid, production-ready
22
`CREATE OR REPLACE PROPERTY GRAPH` DDL definition while keeping existing
23
relational tables intact.
24
25
## Usage Attribution
26
27
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you MUST
28
read and follow the instructions in
29
[Usage Attribution](references/attribution.md).
30
31
## Prerequisites & Cloud Environment Setup
32
33
When inspecting a live Spanner instance or verifying DDL (see `spanner-basics`
34
for general Spanner instance provisioning and MCP setup):
35
36
1. **Google Cloud SDK (`gcloud`)**: Ensure the CLI is installed (see
37
[Install the Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)).
38
2. **Project, Billing & API**: Verify an active Google Cloud project with
39
billing enabled (required even when provisioning a free trial instance) is
40
configured (`gcloud config set project {project_id}`) and, after the user
41
confirms, enable the Spanner API
42
(`gcloud services enable spanner.googleapis.com`). Ask the user before
43
changing the active project, billing, or enabled APIs, or creating or
44
deleting instances, because these commands change the user's Google Cloud
45
environment and can incur costs.
46
3. **Authentication & IAM Roles**: Authenticate via `gcloud auth login` or
47
`gcloud auth application-default login` (or `GOOGLE_APPLICATION_CREDENTIALS`
48
for service accounts). Listing instances/databases requires
49
`roles/spanner.viewer`, inspecting DDL requires
50
`roles/spanner.databaseReader`, and applying `CREATE VIEW` /
51
`CREATE PROPERTY GRAPH` DDL requires `roles/spanner.databaseAdmin`.
52
4. **Instance Region & Pricing**: For sandbox test instances, default to
53
`regional-us-central1` unless specified otherwise (see
54
[Spanner instance configurations](https://docs.cloud.google.com/spanner/docs/instance-configurations.md.txt),
55
[Google Cloud locations](https://cloud.google.com/about/locations),
56
[Spanner pricing](https://cloud.google.com/spanner/pricing), and
57
[Google Cloud pricing](https://cloud.google.com/pricing)).
58
59
---
60
61
## Core Principles
62
63
1. **Zero Data Duplication**: Spanner Graph maps existing relational tables or
64
SQL views directly into graph nodes and edges via `CREATE PROPERTY GRAPH`
65
metadata—without copying data or breaking existing SQL applications.
66
2. **Preserve Existing Tables**: Treat all existing relational tables as
67
read-only inputs. Do not drop, rename, or alter existing columns or primary
68
keys when adding a property graph view. If an implicit relationship requires
69
key transformation (for example, unnesting an array or casting mismatched key
70
types), define a new SQL bridge view
71
(`CREATE VIEW ... SQL SECURITY INVOKER AS ...` by default, or
72
`SQL SECURITY DEFINER` when row-level access control is needed) and bind the
73
edge or node to that view.
74
3. **100% Table Accounting**: Account for every relational table in the input
75
schema—either mapped into `NODE TABLES` / `EDGE TABLES` or explicitly listed
76
as excluded (such as pure system audit logs, schema migration state tables,
77
or unlinked lookup tables).
78
79
---
80
81
## Step-by-Step Conversion Workflow
82
83
### Step 1: Discover or Parse the Relational Schema
84
85
- **If the user provides DDL statements in the prompt**, parse all
86
`CREATE TABLE`, `PRIMARY KEY`, `INTERLEAVE IN PARENT`, and `FOREIGN KEY`
87
definitions directly.
88
- **If the user provides a live Spanner instance and database ID** (or a Google
89
Cloud Console URL containing
90
`instances/{instance_id}/databases/{database_id}?project={project_id}`),
91
extract `project`, `instance`, and `database` and retrieve the live DDL using
92
the read-only `gcloud` command:
93
94
```bash
95
gcloud spanner databases ddl describe {database_id} \
96
--instance={instance_id} \
97
--project={project_id}
98
```
99
100
- **Live-Database Safety Rule**: `gcloud spanner databases ddl describe` is
101
read-only and safe to run automatically, whereas applying `CREATE VIEW` or
102
`CREATE OR REPLACE PROPERTY GRAPH` via `gcloud spanner databases ddl update`
103
mutates the live database—always ask for **explicit user confirmation**
104
before running `gcloud spanner databases ddl update` (and state this
105
confirmation requirement clearly in your response even if `ddl describe`
106
fails due to missing credentials or network access).
107
- See [references/cloud-spanner-guide.md](references/cloud-spanner-guide.md)
108
for environment discovery, emulator setup, and verification workflows.
109
110
### Step 2: Classify Relational Tables into Nodes and Edges
111
112
Apply the structural classification rules in
113
[references/patterns.md](references/patterns.md):
114
115
1. **Core Entity Tables -> `NODE TABLES`**:
116
- Tables representing domain nouns (`Users`, `Accounts`, `Products`,
117
`Devices`, `Documents`) become node tables.
118
- Use the table's full `PRIMARY KEY` as the node `KEY (...)`.
119
2. **Pure or Attributed M:N Junction Tables -> `EDGE TABLES`**:
120
- Tables that link two entity keys (such as
121
`ProjectAssignments(emp_id, project_id)` or `WireTransfers(transfer_id)`
122
with `src_account_id` and `dst_account_id`) become edge tables.
123
- If the table also represents an entity referenced by other tables (for
124
example, `Orders` is a child of `Customers` and a parent of `OrderItems`),
125
map `Orders` as **both** a `NODE TABLE` (`Orders AS OrderNode`) and an
126
`EDGE TABLE` (`Orders AS PlacedOrder`).
127
3. **1:N Foreign Keys and Interleaved Parent-Child Tables -> `EDGE TABLES`
128
(`Table AS Edge`)**:
129
- An entity table `B` with a foreign key (or interleaved parent key prefix)
130
referencing `A` can simultaneously act as a `NODE TABLE` (`B AS NodeB`) and
131
an `EDGE TABLE` (`B AS EdgeBA`) connecting `B` to `A` (or `A` to `B`).
132
- **Self-Referential Hierarchies**: A table like
133
`Employees(emp_id, manager_id)` maps to `Employees AS Employee` in
134
`NODE TABLES` and `Employees AS ReportsToEdge` in `EDGE TABLES`
135
(`SOURCE KEY (emp_id) REFERENCES Employee(emp_id)` and
136
`DESTINATION KEY (manager_id) REFERENCES Employee(emp_id)`).
137
4. **Implicit Relationships (Arrays, JSON, Polymorphic Keys) -> Bridge Views**:
138
- When relationships are embedded in `ARRAY<INT64>` columns, JSON fields, or
139
type-mismatched keys (`INT64` vs. `STRING`), create a SQL bridge view that
140
flattens and projects `(edge_key, src_key, dst_key)` and register the view
141
in `EDGE TABLES` with an explicit `KEY (...)`.
142
- **View Security (`INVOKER` vs. `DEFINER`)**: Every Spanner view requires a
143
`SQL SECURITY` clause. `SQL SECURITY INVOKER` is the common default when
144
callers already hold permissions on the underlying tables, whereas
145
`SQL SECURITY DEFINER` is supported when you need row-level / fine-grained
146
access control so callers can query the graph view without direct
147
base-table grants.
148
- **View Key Uniqueness & `validate_element_key_uniqueness`**: By default,
149
Spanner syntactically verifies that a view's declared `KEY` is unique
150
(either a single base table's primary key or matched by `SELECT DISTINCT` /
151
`GROUP BY`), failing otherwise with
152
`cannot verify the specified element key ... is unique`. Use
153
`SELECT DISTINCT` (or `GROUP BY` the key columns) when inputs can contain
154
duplicate keys (such as duplicate elements inside an `ARRAY`); if you know
155
the view's `KEY` is **already semantically unique** (for example, a
156
key-preserving `JOIN` or `UNNEST(...) WITH OFFSET`), you can instead append
157
`OPTIONS (validate_element_key_uniqueness = false)` to
158
`CREATE PROPERTY GRAPH` to skip syntactic validation without extra
159
`DISTINCT` / `GROUP BY` overhead (you remain responsible for ensuring keys
160
are unique in data).
161
162
### Step 3: Decide Graph Scoping (Unified vs. Multi-Graph)
163
164
- **Default to 1 Unified Property Graph** when tables share a connected domain.
165
- **Recommend Multiple Property Graphs** only when the database contains
166
completely disconnected business domains or exceeds ~12+ distinct node/edge
167
types where domain-specific subgraphs improve query ergonomics.
168
169
### Step 4: Author the `CREATE OR REPLACE PROPERTY GRAPH` DDL
170
171
Follow the exact syntax and structural invariants in
172
[references/spanner-graph-ddl-syntax.md](references/spanner-graph-ddl-syntax.md)
173
and [references/structural-invariants.md](references/structural-invariants.md):
174
175
```sql
176
CREATE OR REPLACE PROPERTY GRAPH GraphName
177
NODE TABLES (
178
TableName AS NodeAlias
179
KEY (pk_col1, pk_col2)
180
LABEL NodeLabel
181
)
182
EDGE TABLES (
183
EdgeTableName AS EdgeAlias
184
KEY (edge_pk_col1, edge_pk_col2)
185
SOURCE KEY (src_fk_col1) REFERENCES SourceNodeAlias(src_pk_col1)
186
DESTINATION KEY (dst_fk_col1) REFERENCES DestNodeAlias(dst_pk_col1)
187
LABEL EdgeLabel
188
);
189
```
190
191
#### Critical DDL Invariants Checklist
192
193
- `NODE TABLES` must be declared **before** `EDGE TABLES`.
194
- Every `NodeAlias` and `EdgeAlias` must be **globally unique** across the
195
entire `CREATE PROPERTY GRAPH` statement (if a table is used as both a node
196
and an edge, give them distinct aliases, e.g., `Orders AS OrderNode` and
197
`Orders AS PlacedOrderEdge`).
198
- **Decouple Edge Identity (`KEY`) from Endpoint Topology (`SOURCE KEY` /
199
`DESTINATION KEY`)**:
200
- `KEY (...)` uniquely identifies the edge row in the backing table or view
201
(for example, `KEY (transfer_id)` or `KEY (src_id, dst_id, transfer_ts)`),
202
while `SOURCE KEY` and `DESTINATION KEY` specify the endpoints. Spanner
203
enforces uniqueness: on a table, a custom `KEY` must contain all primary key
204
columns or match a `UNIQUE` index (so `KEY (src_id, dst_id, transfer_ts)` on
205
a table whose primary key is `transfer_id` fails unless such an index
206
exists). Rows where any `KEY`, `SOURCE KEY`, or `DESTINATION KEY` column is
207
`NULL` are silently skipped by `MATCH`.
208
- In `SOURCE KEY (...) REFERENCES NodeAlias(...)` and
209
`DESTINATION KEY (...) REFERENCES NodeAlias(...)`, the target after
210
`REFERENCES` must be the **`NodeAlias`** (not the underlying relational
211
table name if an alias was used, and not the `LABEL` name), and the column
212
count and data types must match the referenced node's `KEY` 1-to-1. Spanner
213
does not always enforce the count: with an explicit column list it accepts a
214
partial composite key, and each edge then silently matches every node
215
sharing that value.
216
- **Property Exposure (Default `ALL COLUMNS` vs. Explicit `PROPERTIES (...)` /
217
`NO PROPERTIES`)**:
218
- By default, omitting the `PROPERTIES` clause (implicit
219
`PROPERTIES ALL COLUMNS`) exposes all columns of the input table and is
220
concise when a table has its own label and non-conflicting column types.
221
- Use explicit `PROPERTIES (col1 [AS alias], ...)`,
222
`PROPERTIES ALL COLUMNS EXCEPT (...)`, or `NO PROPERTIES` in four
223
relational-conversion cases: (1) **cross-table property type conflicts**
224
(aliasing colliding column names), (2) **shared `LABEL`s** across tables,
225
(3) **dual `Table AS Node` + `Table AS Edge` or pure junction mappings**
226
(`NO PROPERTIES` or edge-only columns so node attributes are not duplicated
227
onto edges), and (4) **excluding internal/sensitive columns or avoiding
228
duplicate exposure of a `DYNAMIC PROPERTIES (json_col)` column**
229
(`PROPERTIES ALL COLUMNS EXCEPT (json_col)`).
230
- If two elements share the same `LABEL` name, they must expose the **exact
231
same set of property names and data types** under that label.
232
- A property name must have **one data type across the whole graph**, even
233
under different labels or on node vs. edge tables (for example, `id INT64`
234
in one table and `id STRING` in another fails with
235
`The property declaration of 'id' has type conflicts`). Alias
236
(`id AS user_id`) or `CAST` one side.
237
- **Optional Reverse Edge Alias (Naming Only)**:
238
- A single physical edge table can be registered a second time in
239
`EDGE TABLES` under a reverse alias (swapping `SOURCE KEY` and
240
`DESTINATION KEY`) when the domain needs a distinct directional label. Don't
241
add one for performance: for undirected traversals use `-[e:LABEL]-` plus a
242
reverse index; querying a swapped-key alias as a label union forces a union
243
across two edge definitions at every hop, which is slower than `-[e:LABEL]-`
244
on quantified paths.
245
246
### Step 5: Verify the DDL and Provide Recommendations
247
248
1. **Verify the DDL** (when a target Spanner database or local emulator is
249
available; see
250
[references/cloud-spanner-guide.md](references/cloud-spanner-guide.md)).
251
Never apply DDL to a shared or production database without explicit user
252
confirmation.
253
2. **Present a Structured 5-Part Deliverable** (modeled in
254
[references/synthesized-conversions.md](references/synthesized-conversions.md)):
255
- **Part 1: Graph Extension Summary & Mapping Matrix** (100% accounting of
256
included and excluded tables).
257
- **Part 2: Complete Executable Spanner Graph DDL** (any required
258
`CREATE VIEW ... SQL SECURITY {INVOKER | DEFINER}` statements followed by
259
`CREATE OR REPLACE PROPERTY GRAPH`).
260
- **Part 3: Performance & Indexing Recommendations** (such as
261
reverse-traversal secondary indexes
262
`ON EdgeTable (dst_key, src_key) INTERLEAVE IN DestNodeTable` or
263
`STORING (...)`, simplifying over-wide composite keys on junction tables,
264
and high-degree hub foreign-key considerations).
265
- **Part 4: Sample ISO GQL Queries** using
266
`GRAPH GraphName MATCH ... RETURN ...` (see
267
[references/gql-cheat-sheet.md](references/gql-cheat-sheet.md)).
268
- **Part 5: Schema Verification Status**.
269
270
---
271
272
## Reference Documentation
273
274
- **[Spanner Discovery Guide](references/cloud-spanner-guide.md)**: Extracting
275
DDL from Spanner via `gcloud`, parsing console URLs, and validating
276
`CREATE PROPERTY GRAPH` on a sandbox or Spanner Emulator.
277
- **[Relational-to-Graph Mapping Patterns](references/patterns.md)**: Detailed
278
rules for classifying entity tables, junction tables, interleaved hierarchies,
279
self-referential FKs, polymorphic tables, and SQL bridge views.
280
- **[Spanner Graph DDL Syntax](references/spanner-graph-ddl-syntax.md)**: Exact
281
BNF grammar and syntax rules for `CREATE PROPERTY GRAPH`, `NODE TABLES`,
282
`EDGE TABLES`, `KEY`, and `PROPERTIES`.
283
- **[Structural Invariants](references/structural-invariants.md)**: How to
284
prevent and fix the 8 most common Spanner Graph DDL mistakes (alias
285
collisions, shared-label and graph-wide property type conflicts, partial or
286
mismatched key references, unverifiable view keys, and custom key uniqueness),
287
with the actual Spanner error messages.
288
- **[ISO GQL Cheat Sheet](references/gql-cheat-sheet.md)**: Quick syntax
289
reference for writing valid Spanner Graph ISO GQL queries (`MATCH`,
290
`WHERE`/`FILTER`, quantified paths `{m,n}`, `NEXT`, `RETURN`).
291
- **[Synthesized Examples](references/synthesized-conversions.md)**: Four
292
complete relational-to-property-graph conversion examples (E-Commerce,
293
Financial AML, Enterprise Org Matrix, and Threat Intelligence).
294
- **Official Spanner Graph Schema Design Documentation**:
295
[Spanner Graph schema design best practices](https://docs.cloud.google.com/spanner/docs/graph/best-practices-designing-schema.md.txt)
296
297
If you need product information that's not found in these references, use the
298
`search_documents` tool of the Developer Knowledge MCP server.
299

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…