Table¶
Contained within this file are experimental interfaces for working with the Synapse Python Client. Unless otherwise noted these interfaces are subject to change at any time. Use at your own risk.
Example Script¶
Working with tables
"""The purpose of this script is to demonstrate how to use the new OOP interface for tables.
The following actions are shown in this script:
1. Creating a table
2. Storing a table
3. Getting a table
4. Storing rows in a table
5. Querying for data from a table
6. Deleting a row from a table
7. Deleting a table
"""
import csv
import os
import random
import string
from datetime import date, datetime, timedelta, timezone
import synapseclient
from synapseclient.models import Column, ColumnType, CsvResultFormat, Row, Table
PROJECT_ID = "syn52948289"
syn = synapseclient.Synapse(debug=True)
syn.login()
def write_random_csv_with_data(path: str):
randomized_data_columns = {
"my_string_column": str,
"my_integer_column": int,
"my_double_column": float,
"my_boolean_column": bool,
}
# Generate randomized data
data = {}
for name, type in randomized_data_columns.items():
if type == int:
data[name] = [random.randint(0, 100) for _ in range(10)]
elif type == float:
data[name] = [random.uniform(0, 100) for _ in range(10)]
elif type == bool:
data[name] = [bool(random.getrandbits(1)) for _ in range(10)]
elif type == str:
data[name] = [
"".join(random.choices(string.ascii_uppercase + string.digits, k=5))
for _ in range(10)
]
with open(path, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
# Write column names
writer.writerow(data.keys())
# Write data
for i in range(10):
writer.writerow([values[i] for values in data.values()])
def store_table():
# Creating annotations for my table ==================================================
annotations_for_my_table = {
"my_single_key_string": "a",
"my_key_string": ["b", "a", "c"],
"my_key_bool": [False, False, False],
"my_key_double": [1.2, 3.4, 5.6],
"my_key_long": [1, 2, 3],
"my_key_date": [date.today(), date.today() - timedelta(days=1)],
"my_key_datetime": [
datetime.today(),
datetime.today() - timedelta(days=1),
datetime.now(tz=timezone(timedelta(hours=-5))),
datetime(2023, 12, 7, 13, 0, 0, tzinfo=timezone(timedelta(hours=0))),
datetime(2023, 12, 7, 13, 0, 0, tzinfo=timezone(timedelta(hours=-7))),
],
}
# Creating columns for my table ======================================================
columns = [
Column(id=None, name="my_string_column", column_type=ColumnType.STRING),
Column(id=None, name="my_integer_column", column_type=ColumnType.INTEGER),
Column(id=None, name="my_double_column", column_type=ColumnType.DOUBLE),
Column(id=None, name="my_boolean_column", column_type=ColumnType.BOOLEAN),
]
# Creating a table ===============================================================
table = Table(
name="my_first_test_table",
columns=columns,
parent_id=PROJECT_ID,
annotations=annotations_for_my_table,
)
table = table.store_schema()
print("Table created:")
print(table)
# Getting a table =================================================================
copy_of_table = Table(id=table.id)
copy_of_table = copy_of_table.get()
print("Table retrieved:")
print(copy_of_table)
# Updating annotations on my table ===============================================
copy_of_table.annotations["my_key_string"] = ["new", "values", "here"]
stored_table = copy_of_table.store_schema()
print("Table updated:")
print(stored_table)
# Storing data to a table =========================================================
name_of_csv = "my_csv_file_with_random_data"
path_to_csv = os.path.join(os.path.expanduser("~/temp"), f"{name_of_csv}.csv")
write_random_csv_with_data(path_to_csv)
csv_path = copy_of_table.store_rows_from_csv(csv_path=path_to_csv)
print("Stored data to table from CSV:")
print(csv_path)
# Querying for data from a table =================================================
destination_csv_location = os.path.expanduser("~/temp/my_query_results")
table_id_to_query = copy_of_table.id
Table.query(
query=f"SELECT * FROM {table_id_to_query}",
result_format=CsvResultFormat(download_location=destination_csv_location),
)
print(f"Created results at: {destination_csv_location}")
# Deleting rows from a table =====================================================
copy_of_table.delete_rows(rows=[Row(row_id=1)])
# Deleting a table ===============================================================
table_to_delete = Table(
name="my_test_table_I_want_to_delete",
columns=columns,
parent_id=PROJECT_ID,
).store_schema()
table_to_delete.delete()
store_table()
API Reference¶
synapseclient.models.Table
dataclass
¶
Bases: TableSynchronousProtocol
, AccessControllable
A Table represents the metadata of a table.
ATTRIBUTE | DESCRIPTION |
---|---|
id |
The unique immutable ID for this table. A new ID will be generated for new Tables. Once issued, this ID is guaranteed to never change or be re-issued |
name |
The name of this table. Must be 256 characters or less. Names may only contain: letters, numbers, spaces, underscores, hyphens, periods, plus signs, apostrophes, and parentheses |
parent_id |
The ID of the Entity that is the parent of this table. |
columns |
The columns of this table. |
description |
The description of this entity. Must be 1000 characters or less. |
etag |
Synapse employs an Optimistic Concurrency Control (OCC) scheme to handle concurrent updates. Since the E-Tag changes every time an entity is updated it is used to detect when a client's current representation of an entity is out-of-date. |
created_on |
The date this table was created. |
created_by |
The ID of the user that created this table. |
modified_on |
The date this table was last modified. In YYYY-MM-DD-Thh:mm:ss.sssZ format |
modified_by |
The ID of the user that last modified this table. |
version_number |
The version number issued to this version on the object. |
version_label |
The version label for this table |
version_comment |
The version comment for this table |
is_latest_version |
If this is the latest version of the object. |
is_search_enabled |
When creating or updating a table or view specifies if full text search should be enabled. Note that enabling full text search might slow down the indexing of the table or view. |
activity |
The Activity model represents the main record of Provenance in Synapse. It is analygous to the Activity defined in the W3C Specification on Provenance. Activity cannot be removed during a store operation by setting it to None. You must use: synapseclient.models.Activity.delete_async or [synapseclient.models.Activity.disassociate_from_entity_async][]. |
annotations |
Additional metadata associated with the table. The key is the name
of your desired annotations. The value is an object containing a list of
values (use empty list to represent no values for key) and the value type
associated with all values in the list. To remove all annotations set this
to an empty dict
TYPE:
|
Source code in synapseclient/models/table.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 |
|
Functions¶
get
¶
Get the metadata about the table from synapse.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Table
|
The Table instance stored in synapse. |
Source code in synapseclient/models/protocols/table_protocol.py
88 89 90 91 92 93 94 95 96 97 98 99 |
|
store_schema
¶
Store non-row information about a table including the columns and annotations.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Table
|
The Table instance stored in synapse. |
Source code in synapseclient/models/protocols/table_protocol.py
75 76 77 78 79 80 81 82 83 84 85 86 |
|
store_rows_from_csv
¶
Takes in a path to a CSV and stores the rows to Synapse.
PARAMETER | DESCRIPTION |
---|---|
csv_path
|
The path to the CSV to store.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
str
|
The path to the CSV that was stored. |
Source code in synapseclient/models/protocols/table_protocol.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
delete_rows
¶
Delete rows from a table.
PARAMETER | DESCRIPTION |
---|---|
rows
|
The rows to delete.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
None
|
None |
Source code in synapseclient/models/protocols/table_protocol.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
|
query
classmethod
¶
query(query: str, result_format: Union[CsvResultFormat, RowsetResultFormat] = None, *, synapse_client: Optional[Synapse] = None) -> Union[CsvFileTable, TableQueryResult, None]
Query for data on a table stored in Synapse.
PARAMETER | DESCRIPTION |
---|---|
query
|
The query to run.
TYPE:
|
result_format
|
The format of the results. Defaults to CsvResultFormat().
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Union[CsvFileTable, TableQueryResult, None]
|
The results of the query. |
Source code in synapseclient/models/protocols/table_protocol.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
|
delete
¶
Delete the table from synapse.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
None
|
None |
Source code in synapseclient/models/protocols/table_protocol.py
101 102 103 104 105 106 107 108 109 110 111 112 |
|
get_permissions
¶
get_permissions(*, synapse_client: Optional[Synapse] = None) -> Permissions
Get the permissions that the caller has on an Entity.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Permissions
|
A Permissions object |
Using this function:
Getting permissions for a Synapse Entity
permissions = File(id="syn123").get_permissions()
Getting access types list from the Permissions object
permissions.access_types
Source code in synapseclient/models/protocols/access_control_protocol.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|
get_acl
¶
Get the ACL that a user or group has on an Entity.
PARAMETER | DESCRIPTION |
---|---|
principal_id
|
Identifier of a user or group (defaults to PUBLIC users)
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
List[str]
|
An array containing some combination of ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE', 'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS'] or an empty array |
Source code in synapseclient/models/protocols/access_control_protocol.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
|
set_permissions
¶
set_permissions(principal_id: int = None, access_type: List[str] = None, modify_benefactor: bool = False, warn_if_inherits: bool = True, overwrite: bool = True, *, synapse_client: Optional[Synapse] = None) -> Dict[str, Union[str, list]]
Sets permission that a user or group has on an Entity. An Entity may have its own ACL or inherit its ACL from a benefactor.
PARAMETER | DESCRIPTION |
---|---|
principal_id
|
Identifier of a user or group.
TYPE:
|
access_type
|
Type of permission to be granted. One or more of CREATE, READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS. Defaults to ['READ', 'DOWNLOAD'] |
modify_benefactor
|
Set as True when modifying a benefactor's ACL
TYPE:
|
warn_if_inherits
|
Set as False, when creating a new ACL. Trying to modify the ACL of an Entity that inherits its ACL will result in a warning
TYPE:
|
overwrite
|
By default this function overwrites existing permissions for the specified user. Set this flag to False to add new permissions non-destructively.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Dict[str, Union[str, list]]
|
An Access Control List object |
Setting permissions
Grant all registered users download access
File(id="syn123").set_permissions(principal_id=273948, access_type=['READ','DOWNLOAD'])
Grant the public view access
File(id="syn123").set_permissions(principal_id=273949, access_type=['READ'])
Source code in synapseclient/models/protocols/access_control_protocol.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
|