Skip to content

Commit 0d177ff

Browse files
tpellissierclaude
andcommitted
Make relationships example idempotent
Add cleanup_previous_run() to automatically delete any existing relationships and tables from previous runs before creating new ones. This makes the example safe to run multiple times without manual cleanup. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent f070270 commit 0d177ff

1 file changed

Lines changed: 61 additions & 21 deletions

File tree

examples/advanced/relationships.py

Lines changed: 61 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,49 @@ def log_call(description):
3838
print(f"\n-> {description}")
3939

4040

41-
def delete_table_if_exists(client, table_name):
42-
"""Delete a table only if it exists."""
43-
if client.get_table_info(table_name):
44-
client.delete_table(table_name)
45-
print(f" (Cleaned up existing table: {table_name})")
46-
return True
41+
def delete_relationship_if_exists(client, schema_name):
42+
"""Delete a relationship by schema name if it exists."""
43+
rel = client.get_relationship(schema_name)
44+
if rel:
45+
rel_id = rel.get("MetadataId")
46+
if rel_id:
47+
client.delete_relationship(rel_id)
48+
print(f" (Cleaned up existing relationship: {schema_name})")
49+
return True
4750
return False
4851

4952

53+
def cleanup_previous_run(client):
54+
"""Clean up any resources from a previous run to make the example idempotent."""
55+
print("\n-> Checking for resources from previous runs...")
56+
57+
# Known relationship names created by this example
58+
relationships = [
59+
"new_Department_Employee",
60+
"contact_new_employee_new_ManagerId",
61+
"new_employee_project",
62+
]
63+
64+
# Known table names created by this example
65+
tables = ["new_Employee", "new_Department", "new_Project"]
66+
67+
# Delete relationships first (required before tables can be deleted)
68+
for rel_name in relationships:
69+
try:
70+
delete_relationship_if_exists(client, rel_name)
71+
except Exception as e:
72+
print(f" [WARN] Could not delete relationship {rel_name}: {e}")
73+
74+
# Delete tables
75+
for table_name in tables:
76+
try:
77+
if client.get_table_info(table_name):
78+
client.delete_table(table_name)
79+
print(f" (Cleaned up existing table: {table_name})")
80+
except Exception as e:
81+
print(f" [WARN] Could not delete table {table_name}: {e}")
82+
83+
5084
def backoff(op, *, delays=(0, 2, 5, 10, 20, 20)):
5185
"""Retry helper with exponential backoff."""
5286
last = None
@@ -104,15 +138,23 @@ def main():
104138
print(f"[OK] Connected to: {base_url}")
105139

106140
# ============================================================================
107-
# 2. CREATE SAMPLE TABLES
141+
# 2. CLEANUP PREVIOUS RUN (Idempotency)
142+
# ============================================================================
143+
print("\n" + "=" * 80)
144+
print("2. Cleanup Previous Run (Idempotency)")
145+
print("=" * 80)
146+
147+
cleanup_previous_run(client)
148+
149+
# ============================================================================
150+
# 3. CREATE SAMPLE TABLES
108151
# ============================================================================
109152
print("\n" + "=" * 80)
110-
print("2. Create Sample Tables")
153+
print("3. Create Sample Tables")
111154
print("=" * 80)
112155

113156
# Create a parent table (Department)
114157
log_call("Creating 'new_Department' table")
115-
delete_table_if_exists(client, "new_Department")
116158

117159
dept_table = backoff(
118160
lambda: client.create_table(
@@ -127,7 +169,6 @@ def main():
127169

128170
# Create a child table (Employee)
129171
log_call("Creating 'new_Employee' table")
130-
delete_table_if_exists(client, "new_Employee")
131172

132173
emp_table = backoff(
133174
lambda: client.create_table(
@@ -142,7 +183,6 @@ def main():
142183

143184
# Create a project table for many-to-many example
144185
log_call("Creating 'new_Project' table")
145-
delete_table_if_exists(client, "new_Project")
146186

147187
proj_table = backoff(
148188
lambda: client.create_table(
@@ -156,10 +196,10 @@ def main():
156196
print(f"[OK] Created table: {proj_table['table_schema_name']}")
157197

158198
# ============================================================================
159-
# 3. CREATE ONE-TO-MANY RELATIONSHIP (Core SDK API)
199+
# 4. CREATE ONE-TO-MANY RELATIONSHIP (Core SDK API)
160200
# ============================================================================
161201
print("\n" + "=" * 80)
162-
print("3. Create One-to-Many Relationship (Core API)")
202+
print("4. Create One-to-Many Relationship (Core API)")
163203
print("=" * 80)
164204

165205
log_call("Creating lookup field on Employee referencing Department")
@@ -213,10 +253,10 @@ def main():
213253
rel_id_1 = result['relationship_id']
214254

215255
# ============================================================================
216-
# 4. CREATE LOOKUP FIELD (Extension Helper)
256+
# 5. CREATE LOOKUP FIELD (Extension Helper)
217257
# ============================================================================
218258
print("\n" + "=" * 80)
219-
print("4. Create Lookup Field (Extension Helper)")
259+
print("5. Create Lookup Field (Extension Helper)")
220260
print("=" * 80)
221261

222262
log_call("Creating lookup field on Employee referencing Contact as Manager")
@@ -242,10 +282,10 @@ def main():
242282
rel_id_2 = result2['relationship_id']
243283

244284
# ============================================================================
245-
# 5. CREATE MANY-TO-MANY RELATIONSHIP
285+
# 6. CREATE MANY-TO-MANY RELATIONSHIP
246286
# ============================================================================
247287
print("\n" + "=" * 80)
248-
print("5. Create Many-to-Many Relationship")
288+
print("6. Create Many-to-Many Relationship")
249289
print("=" * 80)
250290

251291
log_call("Creating M:N relationship between Employee and Project")
@@ -287,10 +327,10 @@ def main():
287327
rel_id_3 = result3['relationship_id']
288328

289329
# ============================================================================
290-
# 6. QUERY RELATIONSHIP METADATA
330+
# 7. QUERY RELATIONSHIP METADATA
291331
# ============================================================================
292332
print("\n" + "=" * 80)
293-
print("6. Query Relationship Metadata")
333+
print("7. Query Relationship Metadata")
294334
print("=" * 80)
295335

296336
log_call("Retrieving relationship by schema name")
@@ -305,10 +345,10 @@ def main():
305345
print(" Relationship not found")
306346

307347
# ============================================================================
308-
# 7. CLEANUP
348+
# 8. CLEANUP
309349
# ============================================================================
310350
print("\n" + "=" * 80)
311-
print("7. Cleanup")
351+
print("8. Cleanup")
312352
print("=" * 80)
313353

314354
cleanup = input("\nDelete created relationships and tables? (y/n): ").strip().lower()

0 commit comments

Comments
 (0)