terminusdb-client

terminusdb_client

Client

__init__(server_url, user_agent, **kwargs)

The Client constructor.

Parameters
Name Type Description
server_urlstrURL of the server that this client will connect to.
user_agentoptional, strUser agent header when making requests. Defaults to terminusdb-client-python with the version appended.
**kwargsExtra configuration options

_check_connection()

Raise connection InterfaceError if not connected Defaults to check if a db is connected

_generate_commit(msg, author)

Pack the specified commit info into a dict format expected by the server.

Parameters
Name Type Description
msgstrCommit message.
authorstrCommit author.
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client._generate_commit("<message>", "<author>")
{'author': '<author>', 'message': '<message>'}

_get_prefixes()

Get the prefixes for a given database

add_role(role)

Add a new role

Parameters
Name Type Description
roledictThe role dict
Examples
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")
>>> role = {
    "name": "Grand Pubah",
    "action": [
        "branch",
        "class_frame",
        "clone",
        "commit_read_access",
        "commit_write_access",
        "create_database",
        "delete_database",
        "fetch",
        "instance_read_access",
        "instance_write_access",
        "manage_capabilities",
        "meta_read_access",
        "meta_write_access",
        "push",
        "rebase",
        "schema_read_access",
        "schema_write_access"
      ]
  }
>>> client.add_role(role)

add_user(username, password)

Add a new user

Parameters
Name Type Description
usernamestrThe username of the user
passwordstrThe user's password

apply(before_version, after_object, branch)

Diff two different commits and apply changes on branch

Parameters
Name Type Description
before_versionstringBefore branch/commit to compare
after_objectstringAfter branch/commit to compare
branchstringBranch to apply to. Optional.

change_capabilities(capability_change)

Change the capabilities of a certain user

Parameters
Name Type Description
capability_changedictDict for the capability change request. Example: { "operation": "revoke", "scope": "UserDatabase/f5a0ef94469b32e1aee321678436c7dfd5a96d9c476672b3282ae89a45b5200e", "user": "User/admin", "roles": [ "Role/consumer", "Role/admin" ] }

change_role(role)

Change role actions for a particular role

Parameters
Name Type Description
roledictRole dict
Examples
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")
>>> role = {
    "name": "Grand Pubah",
    "action": [
        "branch",
        "class_frame",
        "clone",
        "commit_read_access",
        "commit_write_access",
        "create_database",
        "delete_database",
        "fetch",
        "instance_read_access",
        "instance_write_access",
        "manage_capabilities",
        "meta_read_access",
        "meta_write_access",
        "push",
        "rebase",
        "schema_read_access",
        "schema_write_access"
      ]
  }
>>> client.change_role(role)

change_user_password(username, password)

Change user's password

Parameters
Name Type Description
usernamestrThe username of the user
passwordstrThe new password

clonedb(clone_source, newid, Description, remote_auth)

Clone a remote repository and create a local copy.

Parameters
Name Type Description
clone_sourcestrThe source url of the repo to be cloned.
newidstrIdentifier of the new repository to create.
Descriptionstr, optionalOptional description about the cloned database.
remote_authstr, optionalOptional remote authorization (uses client remote auth otherwise)
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.clonedb("http://terminusdb.com/some_user/test_db", "my_test_db")

close()

Undo connect and close the connection.

commit()

Not implementated: open transactions currently not suportted. Please check back later.

connect(team, db, remote_auth, key, user, use_token, jwt_token, api_token, branch, ref, repo, **kwargs)

Connect to a Terminus server at the given URI with an API key.

Parameters
Name Type Description
teamstrName of the team, default to be "admin"
dboptional, strName of the database connected
remote_authoptional, dictRemote Auth setting
keyoptional, strAPI key for connecting, default to be "root"
useroptional, strName of the user, default to be "admin"
use_tokenboolUse token to connect. If both `jwt_token` and `api_token` is not provided (None), then it will use the ENV variable TERMINUSDB_ACCESS_TOKEN to connect as the API token
jwt_tokenoptional, strThe Bearer JWT token to connect. Default to be None.
api_tokenoptional, strsThe API token to connect. Default to be None.
branchoptional, strBranch to be connected, default to be "main"
refoptional, strRef setting
repooptional, strLocal or remote repo, default to be "local"
**kwargsExtra configuration options.
Examples
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")

copy()

Create a deep copy of this client.

Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> clone = client.copy()
>>> assert client is not clone

create_branch(new_branch_id, empty)

Create a branch starting from the current branch.

Parameters
Name Type Description
new_branch_idstrNew branch identifier.
emptyboolCreate an empty branch if true (no starting commit)

create_database(dbid, team, label, description, prefixes, include_schema)

Create a TerminusDB database by posting a terminus:Database document to the Terminus Server.

Parameters
Name Type Description
dbidstrUnique identifier of the database.
teamstr, optionalID of the Team in which to create the DB (defaults to 'admin')
labelstr, optionalDatabase name.
descriptionstr, optionalDatabase description.
prefixesdict, optionalOptional dict containing ``"@base"`` and ``"@schema"`` keys. @base (str) IRI to use when ``doc:`` prefixes are expanded. Defaults to ``terminusdb:///data``. @schema (str) IRI to use when ``scm:`` prefixes are expanded. Defaults to ``terminusdb:///schema``.
include_schemaboolIf ``True``, a main schema graph will be created, otherwise only a main instance graph will be created.
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.create_database("someDB", "admin", "Database Label", "My Description")

create_organization(org)

Add a new organization

Parameters
Name Type Description
orgstrThe id of the organization

delete_branch(branch_id)

Delete a branch

Parameters
Name Type Description
branch_idstrBranch to delete

delete_database(dbid, team, force)

Delete a TerminusDB database.

Parameters
Name Type Description
dbidstrID of the database to delete
teamstr, optionalthe team in which the database resides (defaults to "admin")
forcebool
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.delete_database("<database>", "<team>")

delete_document(document, graph_type, commit_msg, last_data_version)

Delete the specified document(s)

Parameters
Name Type Description
documentstr or list of strDocument(s) (as dictionary or DocumentTemplate objects) or id(s) of document(s) to be updated.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly

delete_organization(org)

Deletes a specific organization

Parameters
Name Type Description
orgstrThe id of the organization

delete_user(username)

Delete a user

Parameters
Name Type Description
usernamestrThe username of the user

diff()

DEPRECATED

Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> result = client.diff({ "@id" : "Person/Jane", "@type" : "Person", "name" : "Jane"}, { "@id" : "Person/Jane", "@type" : "Person", "name" : "Janine"})
>>> result.to_json = '{ "name" : { "@op" : "SwapValue", "@before" : "Jane", "@after": "Janine" }}'

diff_object(before_object, after_object)

Diff two different objects.

Parameters
Name Type Description
before_objectstringBefore object to compare
after_objectstringAfter object to compare

diff_version(before_version, after_version)

Diff two different versions. Can either be a branch or a commit

Parameters
Name Type Description
before_versionstringCommit or branch of the before version to compare
after_versionstringCommit or branch of the after version to compare

fetch(remote_id)

Fatch the brach from a remote

Parameters
Name Type Description
remote_idstrid of the remote

get_all_branches()

Get all the branches available in the database.

get_all_documents(graph_type, skip, count, as_list, get_data_version, kwargs)

Retrieves all avalibale the documents

Parameters
Name Type Description
graph_typeGraphType, optionalGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
skipintThe starting posiion of the returning results, default to be 0
countint or NoneThe maximum number of returned result, if None (default) it will return all of the avalible result.
as_listboolIf the result returned as list rather than an iterator.
get_data_versionboolIf the version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargsAdditional boolean flags for retriving. Currently avaliable: "prefixed", "unfold"

get_available_roles()

Get the available roles for the current authenticated user

get_class_frame(class_name)

Get the frame of the class of class_name. Provide information about all the avaliable properties of that class.

Parameters
Name Type Description
class_namestrName of the class

get_commit_history(max_history)

Get the whole commit history. Commit history - Commit id, author of the commit, commit message and the commit time, in the current branch from the current commit, ordered backwards in time, will be returned in a dictionary in the follow format: ``` { "commit_id": { "author": "commit_author", "message": "commit_message", "timestamp: <datetime object of the timestamp>" } } ```

Parameters
Name Type Description
max_historyint, optionalmaximum number of commit that would return, counting backwards from your current commit. Default is set to 500. It needs to be nop-negative, if input is 0 it will still give the last commit.

get_database()

Returns metadata (id, organization, label, comment) about the requested database Parameters ---------- dbid : str The id of the database team : str The organization of the database (default self.team)

get_databases()

Returns a list of database metadata records for all databases the user has access to

get_document(iri_id, graph_type, get_data_version, kwargs)

Retrieves the document of the iri_id

Parameters
Name Type Description
iri_idstrIri id for the document that is to be retrieved
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
get_data_versionboolIf the data version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargsAdditional boolean flags for retriving. Currently avaliable: "prefixed", "minimized", "unfold"

get_documents_by_type(doc_type, graph_type, skip, count, as_list, get_data_version, kwargs)

Retrieves the documents by type

Parameters
Name Type Description
doc_typestrSpecific type for the docuemnts that is retriving
graph_typeGraphType, optionalGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
skipintThe starting posiion of the returning results, default to be 0
countint or NoneThe maximum number of returned result, if None (default) it will return all of the avalible result.
as_listboolIf the result returned as list rather than an iterator.
get_data_versionboolIf the version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargsAdditional boolean flags for retriving. Currently avaliable: "prefixed", "unfold"

get_existing_classes()

Get all the existing classes (only ids) in a database.

get_organization(org)

Returns a specific organization

Parameters
Name Type Description
orgstrThe id of the organization

get_organization_user(org, username)

Returns user info related to an organization.

Parameters
Name Type Description
orgstr
usernamestr

get_organization_user_databases(org, username)

Returns the databases available to a user which are inside an organization

Parameters
Name Type Description
orgstr
usernamestr

get_organization_users(org)

Returns a list of users in an organization.

Parameters
Name Type Description
orgstr

get_organizations()

Returns a list of organizations in the database.

get_triples(graph_type)

Retrieves the contents of the specified graph as triples encoded in turtle format

Parameters
Name Type Description
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.

get_user(username)

Get a user

Parameters
Name Type Description
usernamestrThe username of the user

get_users()

Get all users

has_database(dbid, team)

Check whether a database exists

Parameters
Name Type Description
dbidstrThe id of the database
teamstrThe organization of the database (default self.team)

has_doc(doc_id, graph_type)

Check if a certain document exist in a database

Parameters
Name Type Description
doc_idstrId of document to be checked.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.

info()

Get info of a TerminusDB database server

insert_document(document, graph_type, full_replace, commit_msg, last_data_version, compress, raw_json)

Inserts the specified document(s)

Parameters
Name Type Description
documentdict or list of dictDocument(s) to be inserted.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
full_replaceboolIf True then the whole graph will be replaced. WARNING: you should also supply the context object as the first element in the list of documents if using this option.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
compressstr or intIf it is an integer, size of the data larger than this (in bytes) will be compress with gzip in the request (assume encoding as UTF-8, 0 = always compress). If it is `never` it will never compress the data.
raw_jsonboolUpdate as raw json

insert_triples(graph_type, content, commit_msg)

Inserts into the specified graph with the triples encoded in turtle format.

Parameters
Name Type Description
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
contentValid set of triples in Turtle or Trig format.
commit_msgstrCommit message.

list_databases()

Returns a list of database ids for all databases the user has access to

log()

Get commit history of a database Parameters ---------- team : str, optional The team from which the database is. Defaults to the class property. db : str, optional The database. Defaults to the class property. start : int, optional Commit index to start from. Defaults to 0. count : int, optional Amount of commits to get. Defaults to -1 which gets all.

ok()

Check whether the TerminusDB server is still OK. Status is not OK when this function returns false or throws an exception (mostly ConnectTimeout)

optimize(path)

Optimize the specified path.

Parameters
Name Type Description
pathstringPath to optimize, for instance admin/database/_meta for the repo graph.
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.optimize('admin/database') # optimise database branch (here main)
>>> client.optimize('admin/database/_meta') # optimise the repository graph (actually creates a squashed flat layer)
>>> client.optimize('admin/database/local/_commits') # commit graph is optimised

patch(before, patch)

Apply the patch object to the before object and return an after object. Note that this change does not commit changes to the graph.

Parameters
Name Type Description
beforedictObject before to patch
patchPatchPatch object to apply to the dict
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> patch_obj = Patch(json='{"name" : { "@op" : "ValueSwap", "@before" : "Jane", "@after": "Janine" }}')
>>> result = client.patch({ "@id" : "Person/Jane", "@type" : Person", "name" : "Jane"}, patch_obj)
>>> print(result)
'{ "@id" : "Person/Jane", "@type" : Person", "name" : "Janine"}'

patch_resource()

Apply the patch object to the given resource

Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> patch_obj = Patch(json='{"name" : { "@op" : "ValueSwap", "@before" : "Jane", "@after": "Janine" }}')
>>> result = client.patch_resource(patch_obj,branch="main")
>>> print(result)
'["Person/Jane"]'

pull(remote, remote_branch, message, author)

Pull updates from a remote repository to the current database.

Parameters
Name Type Description
remotestrremote to pull from, default "origin"
remote_branchstr, optionalremote branch to pull from, default to be your current barnch
messagestr, optionaloptional commit message
authorstr, optionaloption to overide the author of the operation
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.pull()

push(remote, remote_branch, message, author, remote_auth)

Push changes from a branch to a remote repo

Parameters
Name Type Description
remotestrremote to push to, default "origin"
remote_branchstr, optionalremote branch to push to, default to be your current barnch
messagestr, optionaloptional commit message
authorstr, optionaloption to overide the author of the operation
remote_authdict, optionaloptional remote authorization (uses client remote auth otherwise)
Examples
>>> Client(server="http://localhost:6363").push(remote="origin", remote_branch = "main", author = "admin", message = "commit message"})

query(woql_query, commit_mg, get_data_version, last_data_version, file_dict)

Updates the contents of the specified graph with the triples encoded in turtle format Replaces the entire graph contents

Parameters
Name Type Description
woql_querydict or WOQLQuery objectA woql query as an object or dict
commit_mgstrA message that will be written to the commit log to describe the change
get_data_versionboolIf the data version of the query result(s) should be obtained. If True, the method return the result and the version as a tuple.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
file_dict**deprecated**File dictionary to be associated with post name => filename, for multipart POST
Examples
>>> Client(server="http://localhost:6363").query(woql, "updating graph")

query_document(document_template, graph_type, as_list, get_data_version)

Retrieves all documents that match a given document template

Parameters
Name Type Description
document_templatedictTemplate for the document that is being retrived
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
as_listboolIf the result returned as list rather than an iterator.
get_data_versionboolIf the data version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.

rebase(branch, rebase_source, message, author)

Rebase the current branch onto the specified remote branch. Need to specify one of 'branch','commit' or the 'rebase_source'.

Parameters
Name Type Description
branchstr, optionalthe branch for the rebase
rebase_sourcestr, optionalthe source branch for the rebase
messagestr, optionalthe commit message
authorstr, optionalthe commit author
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.rebase("the_branch")

replace_document(document, graph_type, commit_msg, last_data_version, compress, create, raw_json)

Updates the specified document(s)

Parameters
Name Type Description
documentdict or list of dictDocument(s) to be updated.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
compressstr or intIf it is an integer, size of the data larger than this (in bytes) will be compress with gzip in the request (assume encoding as UTF-8, 0 = always compress). If it is `never` it will never compress the data.
createboolCreate the document if it does not yet exist.
raw_jsonboolUpdate as raw json

reset(commit, soft, use_path)

Reset the current branch HEAD to the specified commit path. If `soft` is not True, it will be a hard reset, meaning reset to that commit in the backend and newer commit will be wipped out. If `soft` is True, the client will only reference to that commit and can be reset to the newest commit when done.

Parameters
Name Type Description
commitstringCommit id or path to the commit (if use_path is True), for instance '234980523ffaf93' or 'admin/database/local/commit/234980523ffaf93'. If not provided, it will reset to the newest commit (useful when need to go back after a soft reset).
softboolFlag indicating if the reset if soft, that is referencing to a previous commit instead of resetting to a previous commit in the backend and wipping newer commits.
use_pathboolWheather or not the commit given is an id or path. Default using id and use_path is False.
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.reset('234980523ffaf93')
>>> client.reset('admin/database/local/commit/234980523ffaf93', use_path=True)

rollback()

Curently not implementated. Please check back later.

set_db(dbid, team)

Set the connection to another database. This will reset the connection.

Parameters
Name Type Description
dbidstrDatabase identifer to set in the config.
teamstrTeam identifer to set in the config. If not passed in, it will use the current one.
Examples
>>> client = Client("http://127.0.0.1:6363")
>>> client.set_db("database1")
'database1'

squash(message, author, reset)

Squash the current branch HEAD into a commit

Parameters
Name Type Description
messagestringMessage for the newly created squash commit
authorstringAuthor of the commit
resetboolPerform reset after squash
Examples
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> client.squash('This is a squash commit message!')

update_document(document, graph_type, commit_msg, last_data_version, compress)

Updates the specified document(s). Add the document if not existed.

Parameters
Name Type Description
documentdict or list of dictDocument(s) to be updated.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
compressstr or intIf it is an integer, size of the data larger than this (in bytes) will be compress with gzip in the request (assume encoding as UTF-8, 0 = always compress). If it is `never` it will never compress the data.

update_triples(graph_type, content, commit_msg)

Updates the contents of the specified graph with the triples encoded in turtle format. Replaces the entire graph contents

Parameters
Name Type Description
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
contentValid set of triples in Turtle or Trig format.
commit_msgstrCommit message.