Skip to content

Commit b6355ff

Browse files
committed
Update to match gcloud/cli examples that exist in the docs
1 parent ca68cf5 commit b6355ff

File tree

1 file changed

+153
-57
lines changed

1 file changed

+153
-57
lines changed

samples/samples/graph_snippets.py

Lines changed: 153 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,8 @@ def create_database_with_property_graph(instance_id, database_id):
113113
id INT64 NOT NULL,
114114
to_id INT64 NOT NULL,
115115
amount FLOAT64,
116-
create_time TIMESTAMP NOT NULL,
116+
create_time TIMESTAMP NOT NULL OPTIONS
117+
(allow_commit_timestamp=true),
117118
order_number STRING(MAX),
118119
FOREIGN KEY (to_id) REFERENCES Account (id)
119120
) PRIMARY KEY (id, to_id, create_time),
@@ -160,24 +161,48 @@ def insert_data(instance_id, database_id):
160161
database = instance.database(database_id)
161162

162163
with database.batch() as batch:
164+
batch.insert(
165+
table="Account",
166+
columns=("id", "create_time", "is_blocked", "nick_name"),
167+
values=[
168+
(7, '2020-01-10T06:22:20.12Z', False, "Vacation Fund"),
169+
(16, '2020-01-27T17:55:09.12Z', True, "Vacation Fund"),
170+
(20, '2020-02-18T05:44:20.12Z', False, "Rainy Day Fund")
171+
],
172+
)
173+
163174
batch.insert(
164175
table="Person",
165-
columns=("id", "name", "country", "city"),
176+
columns=("id", "name", "gender", "birthday", "country", "city"),
166177
values=[
167-
(1, "Izumi", "USA", "Mountain View"),
168-
(2, "Tal", "FR", "Paris"),
178+
(1, "Alex", "male", '1991-12-21T00:00:00.12Z', "Australia"," Adelaide"),
179+
(2, "Dana", "female", '1980-10-31T00:00:00.12Z',"Czech_Republic", "Moravia"),
180+
(3, "Lee", "male", '1986-12-07T00:00:00.12Z', "India", "Kollam")
169181
],
170182
)
171183

172184
batch.insert(
173-
table="Account",
174-
columns=("id", "create_time", "is_blocked", "nick_name"),
185+
table="AccountTransferAccount",
186+
columns=("id", "to_id", "amount", "create_time", "order_number"),
175187
values=[
176-
(1, '2014-09-27T11:17:42.18Z', False, "Savings"),
177-
(2, '2008-07-11T12:30:00.45Z', False, "Checking"),
188+
(7, 16, 300.0, '2020-08-29T15:28:58.12Z', "304330008004315"),
189+
(7, 16, 100.0, '2020-10-04T16:55:05.12Z', "304120005529714"),
190+
(16, 20, 300.0, '2020-09-25T02:36:14.12Z', "103650009791820"),
191+
(20, 7, 500.0, '2020-10-04T16:55:05.12Z', "304120005529714"),
192+
(20, 16, 200.0, '2020-10-17T03:59:40.12Z', "302290001255747")
178193
],
179194
)
180195

196+
batch.insert(
197+
table="PersonOwnAccount",
198+
columns=("id", "account_id", "create_time"),
199+
values=[
200+
(1, 7, '2020-01-10T06:22:20.12Z'),
201+
(2, 20, '2020-01-27T17:55:09.12Z'),
202+
(3, 16, '2020-02-18T05:44:20.12Z')
203+
]
204+
)
205+
181206
print("Inserted data.")
182207

183208

@@ -195,34 +220,92 @@ def insert_data_with_dml(instance_id, database_id):
195220
instance = spanner_client.instance(instance_id)
196221
database = instance.database(database_id)
197222

198-
def insert_owns(transaction):
223+
def insert_accounts(transaction):
199224
row_ct = transaction.execute_update(
200-
"INSERT INTO PersonOwnAccount (id, account_id, create_time) "
201-
" VALUES"
202-
"(1, 1, '2014-09-28T09:23:31.45Z'),"
203-
"(2, 2, '2008-07-12T04:31:18.16Z')"
225+
"INSERT INTO Account (id, create_time, is_blocked) "
226+
" VALUES"
227+
" (1, CAST('2000-08-10 08:18:48.463959-07:52' AS TIMESTAMP), false),"
228+
" (2, CAST('2000-08-12 08:18:48.463959-07:52' AS TIMESTAMP), true)"
204229
)
205230

206-
print("{} record(s) inserted into PersonOwnAccount.".format(row_ct))
231+
print("{} record(s) inserted into Account.".format(row_ct))
207232

208233
def insert_transfers(transaction):
209234
row_ct = transaction.execute_update(
210-
"INSERT INTO AccountTransferAccount (id, to_id, amount, create_time, order_number) "
211-
" VALUES"
212-
"(1, 2, 900, '2024-06-24T10:11:31.26Z', '3LXCTB'),"
213-
"(2, 1, 100, '2024-07-01T12:23:28.11Z', '4MYRTQ')"
235+
"INSERT INTO AccountTransferAccount (id, to_id, create_time, amount) "
236+
" VALUES"
237+
" (1, 2, PENDING_COMMIT_TIMESTAMP(), 100),"
238+
" (1, 1, PENDING_COMMIT_TIMESTAMP(), 200) "
214239
)
215240

216241
print("{} record(s) inserted into AccountTransferAccount.".format(row_ct))
217242

218243

219-
database.run_in_transaction(insert_owns)
244+
database.run_in_transaction(insert_accounts)
220245
database.run_in_transaction(insert_transfers)
221246

222247

223248
# [END spanner_insert_graph_data_with_dml]
224249

225250

251+
# [START spanner_update_graph_data_with_dml]
252+
def update_data_with_dml(instance_id, database_id):
253+
"""Updates sample data from the database using a DML statement."""
254+
# instance_id = "your-spanner-instance"
255+
# database_id = "your-spanner-db-id"
256+
257+
spanner_client = spanner.Client()
258+
instance = spanner_client.instance(instance_id)
259+
database = instance.database(database_id)
260+
261+
def update_accounts(transaction):
262+
row_ct = transaction.execute_update(
263+
"UPDATE Account SET is_blocked = false WHERE id = 2"
264+
)
265+
266+
print("{} record(s) updated.".format(row_ct))
267+
268+
def update_transfers(transaction):
269+
row_ct = transaction.execute_update(
270+
"UPDATE AccountTransferAccount SET amount = 300 WHERE id = 1 AND to_id = 2"
271+
)
272+
273+
print("{} record(s) updated.".format(row_ct))
274+
275+
database.run_in_transaction(update_accounts)
276+
database.run_in_transaction(update_transfers)
277+
278+
279+
# [END spanner_update_graph_data_with_dml]
280+
281+
282+
# [START spanner_update_graph_data_with_graph_query_in_dml]
283+
def update_data_with_graph_query_in_dml(instance_id, database_id):
284+
"""Updates sample data from the database using a DML statement."""
285+
# instance_id = "your-spanner-instance"
286+
# database_id = "your-spanner-db-id"
287+
288+
spanner_client = spanner.Client()
289+
instance = spanner_client.instance(instance_id)
290+
database = instance.database(database_id)
291+
292+
def update_accounts(transaction):
293+
row_ct = transaction.execute_update(
294+
"UPDATE Account SET is_blocked = true "
295+
"WHERE id IN ("
296+
" GRAPH FinGraph"
297+
" MATCH (a:Account WHERE a.id = 1)-[:TRANSFERS]->{1,2}(b:Account)"
298+
" RETURN b.id)"
299+
)
300+
301+
print("{} record(s) updated.".format(row_ct))
302+
303+
database.run_in_transaction(update_accounts)
304+
305+
306+
# [END spanner_update_graph_data_with_graph_query_in_dml
307+
308+
226309
# [START spanner_query_graph_data]
227310
def query_data(instance_id, database_id):
228311
"""Queries sample data from the database using GQL."""
@@ -258,7 +341,7 @@ def query_data_with_parameter(instance_id, database_id):
258341
results = snapshot.execute_sql(
259342
"""Graph FinGraph
260343
MATCH (a:Person)-[o:Owns]->()-[t:Transfers]->()<-[p:Owns]-(b:Person)
261-
WHERE t.amount > @min
344+
WHERE t.amount >= @min
262345
RETURN a.name AS sender, b.name AS receiver, t.amount, t.create_time AS transfer_at""",
263346
params={"min": 500},
264347
param_types={"min": spanner.param_types.INT64},
@@ -271,33 +354,6 @@ def query_data_with_parameter(instance_id, database_id):
271354
# [END spanner_with_graph_query_data_with_parameter]
272355

273356

274-
# [START spanner_delete_data]
275-
def delete_data(instance_id, database_id):
276-
"""Deletes sample data from the given database.
277-
278-
The database, table, and data must already exist and can be created using
279-
`create_database` and `insert_data`.
280-
"""
281-
spanner_client = spanner.Client()
282-
instance = spanner_client.instance(instance_id)
283-
database = instance.database(database_id)
284-
285-
# Delete individual rows
286-
ownerships_to_delete = spanner.KeySet(keys=[[1, 1], [2, 2]])
287-
288-
# Delete a range of rows where the column key is >=3 and <5
289-
transfers_range = spanner.KeyRange(start_closed=[1], end_open=[3])
290-
transfers_to_delete = spanner.KeySet(ranges=[transfers_range])
291-
292-
with database.batch() as batch:
293-
batch.delete("PersonOwnAccount", ownerships_to_delete)
294-
batch.delete("AccountTransferAccount", transfers_to_delete)
295-
296-
print("Deleted data.")
297-
298-
299-
# [END spanner_delete_data]
300-
301357
# [START spanner_delete_graph_data_with_dml]
302358
def delete_data_with_dml(instance_id, database_id):
303359
"""Deletes sample data from the database using a DML statement."""
@@ -309,27 +365,63 @@ def delete_data_with_dml(instance_id, database_id):
309365
instance = spanner_client.instance(instance_id)
310366
database = instance.database(database_id)
311367

312-
def delete_persons(transaction):
368+
def delete_transfers(transaction):
313369
row_ct = transaction.execute_update(
314-
"DELETE FROM Person WHERE True"
370+
"DELETE FROM AccountTransferAccount WHERE id = 1 AND to_id = 2"
315371
)
316372

317373
print("{} record(s) deleted.".format(row_ct))
318374

319375
def delete_accounts(transaction):
320376
row_ct = transaction.execute_update(
321-
"DELETE FROM Account AS a WHERE EXTRACT(YEAR FROM DATE(a.create_time)) >= 2000"
377+
"DELETE FROM Account WHERE id = 2"
322378
)
323379

324380
print("{} record(s) deleted.".format(row_ct))
325381

382+
database.run_in_transaction(delete_transfers)
326383
database.run_in_transaction(delete_accounts)
327-
database.run_in_transaction(delete_persons)
328384

329385

330386
# [END spanner_delete_graph_data_with_dml]
331387

332388

389+
# [START spanner_delete_data]
390+
def delete_data(instance_id, database_id):
391+
"""Deletes sample data from the given database.
392+
393+
The database, table, and data must already exist and can be created using
394+
`create_database` and `insert_data`.
395+
"""
396+
spanner_client = spanner.Client()
397+
instance = spanner_client.instance(instance_id)
398+
database = instance.database(database_id)
399+
400+
# Delete individual rows
401+
ownerships_to_delete = spanner.KeySet(keys=[[1, 7], [2, 20]])
402+
403+
# Delete a range of rows where the column key is >=1 and <8
404+
transfers_range = spanner.KeyRange(start_closed=[1], end_open=[8])
405+
transfers_to_delete = spanner.KeySet(ranges=[transfers_range])
406+
407+
# Delete Account/Person rows, which will also delete the remaining
408+
# AccountTransferAccount and PersonOwnAccount rows because
409+
# AccountTransferAccount and PersonOwnAccount are defined with
410+
# ON DELETE CASCADE
411+
remaining_nodes = spanner.KeySet(all_=True)
412+
413+
with database.batch() as batch:
414+
batch.delete("PersonOwnAccount", ownerships_to_delete)
415+
batch.delete("AccountTransferAccount", transfers_to_delete)
416+
batch.delete("Account", remaining_nodes)
417+
batch.delete("Person", remaining_nodes)
418+
419+
print("Deleted data.")
420+
421+
422+
# [END spanner_delete_data]
423+
424+
333425
if __name__ == "__main__": # noqa: C901
334426
parser = argparse.ArgumentParser(
335427
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
@@ -346,30 +438,34 @@ def delete_accounts(transaction):
346438
help=create_database_with_property_graph.__doc__)
347439
subparsers.add_parser("insert_data", help=insert_data.__doc__)
348440
subparsers.add_parser("insert_data_with_dml", help=insert_data_with_dml.__doc__)
441+
subparsers.add_parser("update_data_with_dml", help=update_data_with_dml.__doc__)
442+
subparsers.add_parser("update_data_with_graph_query_in_dml",
443+
help=update_data_with_graph_query_in_dml.__doc__)
349444
subparsers.add_parser("query_data", help=query_data.__doc__)
350445
subparsers.add_parser(
351446
"query_data_with_parameter", help=query_data_with_parameter.__doc__
352447
)
353-
354448
subparsers.add_parser("delete_data", help=delete_data.__doc__)
355449
subparsers.add_parser("delete_data_with_dml", help=delete_data_with_dml.__doc__)
356450

357451
args = parser.parse_args()
358452

359-
if args.command == "create_instance":
360-
create_instance(args.instance_id)
361-
elif args.command == "create_database_with_property_graph":
453+
if args.command == "create_database_with_property_graph":
362454
create_database_with_property_graph(args.instance_id, args.database_id)
363455
elif args.command == "insert_data":
364456
insert_data(args.instance_id, args.database_id)
365457
elif args.command == "insert_data_with_dml":
366458
insert_data_with_dml(args.instance_id, args.database_id)
459+
elif args.command == "update_data_with_dml":
460+
update_data_with_dml(args.instance_id, args.database_id)
461+
elif args.command == "update_data_with_graph_query_in_dml":
462+
update_data_with_graph_query_in_dml(args.instance_id, args.database_id)
367463
elif args.command == "query_data":
368464
query_data(args.instance_id, args.database_id)
369465
elif args.command == "query_data_with_parameter":
370466
query_data_with_parameter(args.instance_id, args.database_id)
371-
elif args.command == "delete_data":
372-
delete_data(args.instance_id, args.database_id)
373467
elif args.command == "delete_data_with_dml":
374468
delete_data_with_dml(args.instance_id, args.database_id)
469+
elif args.command == "delete_data":
470+
delete_data(args.instance_id, args.database_id)
375471

0 commit comments

Comments
 (0)