JavaScript Client

v12.0.0

The official TerminusDB JavaScript client library for browser and Node.js applications. Build powerful data-driven applications with type-safe database operations.

$npm install @terminusdb/terminusdb-client

WOQLClient

action(actionName, payload)

Sends an action to the server

Parameters
actionNamestringstructure of the action
payloadobjecta request body call
Returns
PromiseA promise that returns the call response object, or an Error if rejected.

addDocument(json, params, dbId, string, lastDataVersion, getDataVersion)

to add a new document or a list of new documents into the instance or the schema graph.

Parameters
jsonobject
paramstypedef.DocParamsPostthe post parameters {@link #typedef.DocParamsPost}
dbIdstringthe dbid
stringmessagethe insert commit message
lastDataVersionstringthe last data version tracking id.
getDataVersionbooleanIf true the function will return object having result and dataVersion.
Returns
PromiseA promise that returns the call response object or object having *result* and *dataVersion* object if ***getDataVersion*** parameter is true, or an Error if rejected.
Example: JavaScript
const json = [{ "@type" : "Class",
             "@id" : "Coordinate",
             "@key" : { '@type' : 'Hash',
             '@fields' : ['x','y'] },
             "x" : "xsd:decimal",
             "y" : "xsd:decimal" },
             { "@type" : "Class",
             "@id" : "Country",
             "@key" : { '@type' : 'Lexical',
                         '@fields' : [name] },
             "name" : "xsd:string",
             "perimeter" : { "@type" : "List",
                             "@class" : "Coordinate" } }]
client.addDocument(json,{"graph_type":"schema"},"mydb","add new schema documents")

//if we would like to override the entire schema
const json = [
{"@base": "terminusdb:///data/",
      "@schema": "terminusdb:///schema#",
      "@type": "@context"
  },
  {
      "@id": "Person",
       "@key": {
          "@type": "Random"
      },
      "@type": "Class",
      "name": {
          "@class": "xsd:string",
          "@type": "Optional"
      }
  }]

// client.addDocument(json,{"graph_type":"schema","full_replace:true"},
      "mydb","update the all schema");

// Here we will pass true to show how to get dataVersion

const response = await client.addDocument(json, {"graph_type": "schema"},
  "mydb",
  "add new schema", '',
  true
)
console.log(response);

 // This will output:
 // {
 //   result: [ ...... ],
 //   dataVersion: 'branch:5fs681tlycnn6jh0ceiqcq4qs89pdfs'
 // }

 // Now we can use the data version we recieved as a response in previous
 // function call and used it is next function call as lastDataVersion

const response1 = await client.addDocument(json, {"graph_type": "schema"},
  "mydb",
  "add new schema", response.dataVersion,
)

api()

Retrieve the URL of the server’s API base that we are currently connected to

Returns
stringthe URL of the TerminusDB server api endpoint we are connected to (typically server() + “api/”)
Example: JavaScript
let api_url = client.api()

apply(beforeVersion, afterVersion, message, matchFinalState, options)

Diff two different commits and apply changes on the current branch/commit. If you would like to change branch or commit before apply use client.checkout("branchName")

Parameters
beforeVersionstringBefore branch/commit to compare
afterVersionstringAfter branch/commit to compare
messagestringapply commit message
matchFinalStatebooleanthe default value is false
optionsobject{keep:{}} Options to send to the apply endpoint
Example: JavaScript
client.checkout("mybranch")
client.apply("mybranch","mybranch_new","merge main").then(result=>{
   console.log(result)
})

author()

Gets the string that will be written into the commit log for the current user

Returns
stringthe current user
Example: JavaScript
client.author()

branch(newBranchId, isEmpty)

Creates a new branch with a TerminusDB database, starting from the current context of the client (branch / ref)

Parameters
newBranchIdstringlocal identifier of the new branch the ID of the new branch to be created
isEmptybooleanif isEmpty is true it will create a empty branch.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.branch("dev")

checkout(branchId)

Gets/Sets the client’s internal branch context value (defaults to ‘main’)

Parameters
branchIdstringthe branch id to set the context to
Returns
stringthe current branch id within the client context

clonedb(cloneSource, newDbId, orgId)

Clones a remote repo and creates a local copy

Parameters
cloneSourcetypedef.CloneSourceDetailsobject describing the source branch to be used as a base
newDbIdstringid of the new cloned database on the local server
orgIdstringid of the local organization that the new cloned database will be created in (in desktop mode this is always “admin”)
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.clonedb({remote_url: "https://my.terminusdb.com/myorg/mydb", label "Cloned DB", comment: "Cloned from mydb"}, newid: "mydb")

connect(params)

You can call this to get the server info or override the start params configuration, this.connectionConfig.server will be used if present, or the promise will be rejected.

Parameters
paramstypedef.ParamsObjTerminusDB Server connection parameters
Returns
Promisethe connection capabilities response object or an error object
Example: JavaScript
client.connect()

copy()

creates a copy of the client with identical internal state and context useful if we want to change context for a particular API call without changing the current client context

Returns
WOQLClientnew client object with identical state to original but which can be manipulated independently
Example: JavaScript
let newClient = client.copy()

createDatabase(dbId, dbDetails, orgId)

Creates a new database in TerminusDB server

Parameters
dbIdstringThe id of the new database to be created
dbDetailstypedef.DbDetailsobject containing details about the database to be created
orgIdstringoptional organization id - if absent default local organization id is used
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
//remember set schema:true if you need to add a schema graph
client.createDatabase("mydb", {label: "My Database", comment: "Testing", schema: true})

createRemote(remoteName, remoteLocation)

Creates a new remote connection for the database

Parameters
remoteNamestringThe name of the remote to create
remoteLocationstringThe URL of the remote repository
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.createRemote("origin", "http://remote.server.com/org/db")

customHeaders(customHeaders)

add extra headers to your request

Parameters
customHeadersobject
Returns
object

databaseInfo(dbName)

Gets the database's details

Parameters
dbNamestringthe datbase name
Returns
objectthe database description object

databases(dbList)

Set/Get the organization's databases list (id, label, comment) that the current user has access to on the server.

Parameters
dbListarraya list of databases the user has access to on the server, each having:
Returns
arraythe organization's databases list
Example: JavaScript
//to get the list of all organization's databases
async function callGetDatabases(){
     await client.getDatabases()
     console.log(client.databases())
}

db(dbId)

Sets / Gets the current database

Parameters
dbIdstringthe database id to set the context to
Returns
string|boolean- the current database or false
Example: JavaScript
client.db("mydb")

deleteBranch(branchId)

Deletes a branch from database

Parameters
branchIdstringlocal identifier of the branch
Returns
PromiseA promise that returns the call response object, or an Error if rejected.

deleteDatabase(dbId, orgId, force)

Deletes a database from a TerminusDB server

Parameters
dbIdstringThe id of the database to be deleted
orgIdstringthe id of the organization to which the database belongs (in desktop use, this will always be “admin”)
forceboolean
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.deleteDatabase("mydb")

deleteDocument(params, dbId, message, lastDataVersion, getDataVersion)

to delete the document

Parameters
paramstypedef.DocParamsDelete
dbIdstringthe database id
messagestringthe delete message
lastDataVersionstringthe last data version tracking id.
getDataVersionbooleanIf true the function will return object having result and dataVersion.
Returns
PromiseA promise that returns the call response object or object having *result* and *dataVersion* object if ***getDataVersion*** parameter is true, or an Error if rejected.
Example: JavaScript
client.deleteDocument({"graph_type":"schema",id:['Country','Coordinate']})


// Here we will pass true to show how to get dataVersion

const response = await client.deleteDocument({"graph_type":"schema",id:['Country','Coordinate']},
  "",
  "",
  "",
  true
)
console.log(response);

 // This will output:
 // {
 //   result: [ ...... ],
 //   dataVersion: 'branch:5fs681tlycnn6jh0ceiqcq4qs89pdfs'
 // }

 // Now we can use the data version we recieved as a response in previous
 // function call and used it is next function call as lastDataVersion

const response1 = await client.deleteDocument({"graph_type":"schema",
  id:['Country','Coordinate']},
  "",
  "",
  response.dataVersion,
)

deleteRemote(remoteName)

Deletes a remote connection

Parameters
remoteNamestringThe name of the remote to delete
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.deleteRemote("origin")

dispatch()

Common request dispatch function

Returns
PromiseA promise that returns the call response object, or an Error if rejected.

fetch(remoteId)

Fetch updates to a remote database to a remote repository with the local database

Parameters
remoteIdstringif of the remote to fetch (eg: 'origin')
Returns
PromiseA promise that returns the call response object, or an Error if rejected.

generateCommitDescriptor(commitId)

Generates the json structure for commit descriptor

Parameters
commitIdstringa valid commit id o

generateCommitInfo(msg, author)

Generates the json structure for commit messages

Parameters
msgstringtextual string describing reason for the change
authorstringoptional author id string - if absent current user id will be used
Returns
object

getBranches(dbId)

get the database collections list

Parameters
dbIdstringthe database id
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.getBranches()

getClassDocuments(dbId)

get all the Document Classes (no abstract or subdocument)

Parameters
dbIdstring
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.getClassDocuments()

getClasses(dbId)

get all the schema classes (documents,subdocuments,abstracts)

Parameters
dbIdstringthe database id
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.getClasses()

getCommitsLog(start, count)

get the database collections list

Parameters
startnumberwhere to start printing the commit information in the log (starting from the head of the current branch)
countnumberThe number of total commit log records to return
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.getCommitsLog(count=10)

getDatabases()

Gets the organization's databases list. If no organization has been set up, the function throws an exception

Returns
Promise
Example: JavaScript
async function callGetDatabases(){
     const dbList = await client.getDatabases()
     console.log(dbList)
}

getDocument(params, dbId, branch, lastDataVersion, getDataVersion, query)

Parameters
paramstypedef.DocParamsGetthe get parameters, you can pass document query search template with the params
dbIdstringthe database id
branchstringthe database branch
lastDataVersionstringthe last data version tracking id.
getDataVersionbooleanIf true the function will return object having result and dataVersion.
queryobjectdocument query search template
Returns
PromiseA promise that returns the call response object or object having *result* and *dataVersion* object if ***getDataVersion*** parameter is true, or an Error if rejected.
Example: JavaScript
//return the schema graph as a json array
client.getDocument({"graph_type":"schema","as_list":true}).then(result={
   console.log(result)
})

//retutn the Country class document from the schema graph
client.getDocument({"graph_type":"schema","as_list":true,"id":"Country"}).then(result={
   console.log(result)
})

//pass a document query template to query the document interface
const queryTemplate = { "name": "Ireland"}
client.getDocument({"as_list":true, "@type":"Country"
           query:queryTemplate}).then(result=>{
   console.log(result)
})


// Here we will pass true to show how to get dataVersion
const response = await client.getDocument({"graph_type":"schema","as_list":true},
  "",
  "",
  "",
  true
)
console.log(response);

 // This will output:
 // {
 //   result: [ ...... ],
 //   dataVersion: 'branch:5fs681tlycnn6jh0ceiqcq4qs89pdfs'
 // }

 // Now we can use the data version we recieved as a response in previous
 // function call and used it is next function call as lastDataVersion

const response1 = await client.getDocument({"graph_type":"schema","as_list":true},
  "",
  "",
  response.dataVersion,
)

getDocumentHistory(id, historyParams)

Get the document's history for a specific database or branch

Parameters
idstringid of document to report history of
historyParamstypedef.DocHistoryParams
Example: JavaScript
//this will return the last 5 commits for the Person/Anna document
client.checkout("mybranch")
client.docHistory("Person/Anna",{start:0,count:5}).then(result=>{
   console.log(result)
})
//this will return the last and the first commit for the Person/Anna document
client.docHistory("Person/Anna",{updated:true,created:true}).then(result=>{
   console.log(result)
})

getEnums(dbId)

get all the Enum Objects

Parameters
dbIdstring
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.getEnums()

getJSONDiff(before, after, options)

Get the patch of difference between two documents.

Parameters
beforeobjectThe current state of JSON document
afterobjectThe updated state of JSON document
optionsobject{keep:{}} Options to send to the diff endpoint. The diff api outputs the changes between the input, in options you can list the properties that you would like to see in the diff result in any case.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.getJSONDiff(
     { "@id": "Person/Jane", "@type": "Person", name: "Jane" },
     { "@id": "Person/Jane", "@type": "Person", name: "Janine" }
 ).then(diffResult=>{
 console.log(diffResult)
})
//result example
//{'@id': 'Person/Jane',
// name: { '@after': 'Janine', '@before': 'Jane', '@op': 'SwapValue' }}

getPrefixes(dbId)

get the database prefixes object

Parameters
dbIdstringthe database id
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.getPrefixes()
//return object example
{
'@base': 'terminusdb:///data/',
'@schema': 'terminusdb:///schema#',
'@type': 'Context'}

getRemote(remoteName)

Gets information about a remote connection

Parameters
remoteNamestringThe name of the remote to retrieve
Returns
PromiseA promise that returns the remote details, or an Error if rejected.
Example: JavaScript
const remote = await client.getRemote("origin")

getSchema(dbId, branch)

get the database schema in json format

Parameters
dbIdstringthe database id
branchstringspecific a branch/collection
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.getSchema()

getSchemaFrame(type, dbId)

The purpose of this method is to quickly discover the supported fields of a particular type.

Parameters
typestringIf given, the type to get information for. If omitted, information for all types is returned
dbIdstringthe database id
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.getSchemaFrame("Country")

getTriples(graphType)

Retrieve the contents of a graph within a TerminusDB as triples, encoded in the turtle (ttl) format

Parameters
graphTypetypedef.GraphTypetype of graph to get triples from, either “instance” or “schema”
Returns
PromiseA promise that returns the call response object (with the contents being a string representing a set of triples in turtle (ttl) format), or an Error if rejected.
Example: JavaScript
const turtle = await client.getTriples("schema", "alt")

getUserOrganizations()

Get the list of the user's organizations and the database related

Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
async funtion callGetUserOrganizations(){
     await getUserOrganizations()
     console.log(client.userOrganizations())
}

getVersionDiff(beforeVersion, afterVersion, id, options)

Get the patch of difference between branches or commits.

Parameters
beforeVersionstringBefore branch/commit to compare
afterVersionstringAfter branch/commit to compare
idstringThe document id to be diffed, if it is omitted all the documents will be compared
optionstypedef.DiffObject{keep:{},count:10,start:0} Options to send to the diff endpoint. The diff api outputs the changes between the input (branches or commits), in options you can list the properties that you would like to see in the diff result in any case.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
//This is to view all the changes between two commits
const beforeCommit = "a73ssscfx0kke7z76083cgswszdxy6l"
const afterCommit = "73rqpooz65kbsheuno5dsayh71x7wf4"

client.getVersionDiff( beforeCommit, afterCommit).then(diffResult=>{
 console.log(diffResult)
})

//This is to view the changes between two commits but only for the given document
client.getVersionDiff( beforeCommit, afterCommit, "Person/Tom").then(diffResult=>{
 console.log(diffResult)
})

//This is to view the changes between a branch (head) and a commit for the given document
client.getVersionDiff("main", afterCommit, "Person/Tom" ).then(diffResult=>{
   console.log(diffResult)
})

//This is to view the changes between two branches with the keep options
const options = {"keep":{"@id":true, "name": true}, start:0, count:10}
client.getVersionDiff("main","mybranch",options).then(diffResult=>{
   console.log(diffResult)
})

getVersionObjectDiff(dataVersion, jsonObject, id, options)

Get the patch of difference between two documents.

Parameters
dataVersionstringThe version from which to compare the object
jsonObjectobjectThe updated state of JSON document
idstringThe document id to be diffed
optionsobject{keep:{}} Options to send to the diff endpoint the diff api outputs the changes between the input, but you can list the properties that you would like to see in the diff result in any case.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
const jsonObj =  { "@id": "Person/Jane", "@type": "Person", name: "Janine" }
client.getVersionObjectDiff("main",jsonObj
     "Person/Jane").then(diffResp=>{
   console.log(diffResp)
})

hasDatabase(orgName, dbName)

Checks if a database exists Returns true if a DB exists and false if it doesn't. Other results throw an exception.

Parameters
orgNamestringthe organization id to set the context to
dbNamestringthe db name to set the context to
Returns
Promise
Example: JavaScript
async function executeIfDatabaseExists(f){
     const hasDB = await client.hasDatabase("admin", "testdb")
     if (hasDB) {
         f()
     }
}

info()

Gets TerminusDB Server Information

Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.info()

insertTriples(graphType, turtle, commitMsg)

Appends the passed turtle to the contents of a graph

Parameters
graphTypestringtype of graph |instance|schema|inference|
turtlestringis a valid set of triples in turtle format (OWL)
commitMsgstringTextual message describing the reason for the update
Returns
PromiseA promise that returns the call response object, or an Error if rejected.

localAuth(newCredential)

Sets/Gets set the database basic connection credential

Parameters
newCredentialtypedef.CredentialObj
Returns
typedef.CredentialObj|boolean
Example: JavaScript
client.localAuth({user:"admin","key":"mykey","type":"basic"})

message(message, pathname)

Sends a message to the server

Parameters
messagestringtextual string
pathnamestringa server path to send the message to
Returns
PromiseA promise that returns the call response object, or an Error if rejected.

optimizeBranch(branchId)

Optimize db branch

Parameters
branchIdstringlocal identifier of the new branch
Returns
PromiseA promise that returns the call response object, or an Error if rejected.

organization(orgId)

Gets/Sets the client’s internal organization context value, if you change the organization name the databases list will be set to empty

Parameters
orgIdstring|booleanthe organization id to set the context to
Returns
string|boolean
Example: JavaScript
client.organization("admin")

patch(before, patch)

Apply a patch object to another object

Parameters
beforeobjectThe current state of JSON document
patchobjectThe patch object
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.patch(
     { "@id" : "Person/Jane", "@type" : "Person", "name" : "Jane"},
     { "name" : { "@op" : "ValueSwap", "@before" : "Jane", "@after": "Janine" }}
 ).then(patchResult=>{
 console.log(patchResult)
})
//result example
//{ "@id" : "Person/Jane", "@type" : "Person", "name" : "Jannet"}

patchResource(patch, message)

Apply a patch object to the current resource

Parameters
patcharrayThe patch object
messagestringThe commit message
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
const patch = [
  {
   "@id": "Obj/id1",
    "name": {
     "@op": "SwapValue",
      "@before": "foo",
      "@after": "bar"
    }
  },
 {
   "@id": "Obj/id2",
    "name": {
      "@op": "SwapValue",
      "@before": "foo",
     "@after": "bar"
    }
 }
]
client.db("mydb")
client.checkout("mybranch")
client.patchResource(patch,"apply patch to mybranch").then(patchResult=>{
 console.log(patchResult)
})
// result example
// ["Obj/id1",
// "Obj/id2"]
// or conflict error 409
// {
// "@type": "api:PatchError",
// "api:status": "api:conflict",
// "api:witnesses": [
//  {
//   "@op": "InsertConflict",
//    "@id_already_exists": "Person/Jane"
//  }
//]
//}

prepareRevisionControlArgs(rc_args)

Adds an author string (from the user object returned by connect) to the commit message.

Parameters
rc_argsobject
Returns
object|boolean

pull(remoteSourceRepo)

Pull changes from a branch on a remote database to a branch on a local database

Parameters
remoteSourceRepotypedef.RemoteRepoDetailsan object describing the source of the pull
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.pull({remote: "origin", remote_branch: "main", message: "Pulling from remote"})

push(remoteTargetRepo)

Push changes from a branch on a local database to a branch on a remote database

Parameters
remoteTargetRepotypedef.RemoteRepoDetailsan object describing the target of the push {remote: "origin", "remote_branch": "main", "author": "admin", "message": "message"}
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.push({remote: "origin", remote_branch: "main", message: "Pulling from remote"})

query(woql, commitMsg, allWitnesses, lastDataVersion, getDataVersion, resources)

Executes a WOQL query on the specified database and returns the results

Parameters
woqlWOQLQueryan instance of the WOQLQuery class
commitMsgstringa message describing the reason for the change that will be written into the commit log (only relevant if the query contains an update)
allWitnessesboolean
lastDataVersionstringthe last data version tracking id.
getDataVersionbooleanIf true the function will return object having result and dataVersion.
resourcesArray.<NamedResourceData>csv resources supplied as strings
Returns
PromiseA promise that returns the call response object or object having *result* and *dataVersion* object if ***getDataVersion*** parameter is true, or an Error if rejected.
Example: JavaScript
const result = await client.query(WOQL.star())

queryDocument(query, params, dbId, branch, lastDataVersion, getDataVersion)

Use {@link #getDocument} instead.

Parameters
queryobjectthe query template
paramstypedef.DocParamsGetthe get parameters
dbIdstringthe database id
branchstringthe database branch
lastDataVersionstringthe last data version tracking id.
getDataVersionbooleanIf true the function will return object having result and dataVersion.
Returns
PromiseA promise that returns the call response object or object having *result* and *dataVersion* object if ***getDataVersion*** parameter is true, or an Error if rejected.
Example: JavaScript
const query = {
  "type": "Person",
  "query": { "age": 42 },
 }
client.queryDocument(query, {"as_list":true})


// Here we will pass true to show how to get dataVersion
const query = {
  "type": "Person",
  "query": { "age": 42 },
 }

const response = await client.queryDocument(query, {"as_list": true}, '', '','',true);
console.log(response);

 // This will output:
 // {
 //   result: [
 //     {
 //       '@id': 'Person/052d60ffbd114bf5e7331b03f07fcb7',
 //       '@type': 'Person',
 //       age: 42,
 //       name: 'John',
 //     },
 //   ],
 //   dataVersion: 'branch:5fs681tlycnn6jh0ceiqcq4qs89pdfs'
 // }

 // Now we can use the data version we recieved as a response in previous
 // query and used it is next query as lastDataVersion
 const query = {
  "type": "Person",
  "query": { "age": 18 },
 }

 const response1 = await client.queryDocument(query, {"as_list": true}, '',
   '',
   response.dataVersion
 );

rebase(rebaseSource)

Merges the passed branch into the current one using the rebase operation

Parameters
rebaseSourceobjectjson describing the source branch to be used as a base
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
//from the branch head
client.rebase({rebase_from: "admin/db_name/local/branch/branch_name", message:
"Merging from dev")
//or from a commit id
client.rebase({rebase_from: "admin/db_name/local/commit/9w8hk3y6rb8tjdy961de3i536ntkqd8",
message: "Merging from dev")

ref(commitId)

Sets / gets the current ref pointer (pointer to a commit within a branch) Reference ID or Commit ID are unique hashes that are created whenever a new commit is recorded

Parameters
commitIdstringthe reference ID or commit ID
Returns
string|booleanthe current commit id within the client context
Example: JavaScript
client.ref("mkz98k2h3j8cqjwi3wxxzuyn7cr6cw7")

remoteAuth(newCredential)

Sets/Gets the jwt token for authentication we need this to connect 2 terminusdb server to each other for push, pull, clone actions

Parameters
newCredentialtypedef.CredentialObj
Returns
typedef.CredentialObj|boolean
Example: JavaScript
client.remoteAuth({"key":"dhfmnmjglkrelgkptohkn","type":"jwt"})

repo(repoId)

Gets / Sets the client’s internal repository context value (defaults to ‘local’)

Parameters
repoIdtypedef.RepoType|stringdefault value is local
Returns
stringthe current repository id within the client context
Example: JavaScript
client.repo("origin")

reset(commitPath)

Reset the current branch HEAD to the specified commit path

Parameters
commitPathstringThe commit path to set the current branch to
Returns
PromiseA promise that returns the call response object, or an Error if rejected.

resetBranch(branchId, commitId)

Reset branch to a commit id, Reference ID or Commit ID are unique hashes that are created whenever a new commit is recorded

Parameters
branchIdstringlocal identifier of the new branch
commitIdstringReference ID or Commit ID
Returns
PromiseA promise that returns the call response object, or an Error if rejected.

resource(resourceType, resourceId)

Generates a resource string for the required context of the current context for "commits" "meta" "branch" and "ref" special resources

Parameters
resourceTypetypedef.ResourceTypethe type of resource string that is required - one of “db”, “meta”, “repo”, “commits”, “branch”, “ref”
resourceIdstringcan be used to specify a specific branch / ref - if not supplied the current context will be used
Returns
stringa resource string for the desired context
Example: JavaScript
const branch_resource = client.resource("branch")

sendCustomRequest(requestType, customRequestURL, payload)

Call a custom Api endpoit

Parameters
requestTypestringThe current state of JSON document
customRequestURLstringThe patch object
payloadobjectthe request payload
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.sendCustomRequest("GET", "http://localhost:3030/changes/").then(result=>{
   console.log(result)
})

server()

Gets the current connected server url it can only be set creating a new WOQLCLient instance

Returns
string

set(params)

Parameters
paramstypedef.ParamsObja object with connection params
Example: JavaScript
sets several of the internal state values in a single call
(similar to connect, but only sets internal client state, does not communicate with server)
client.set({key: "mypass", branch: "dev", repo: "origin"})

setApiKey(accessToken)

set the api key to access the cloud resources

Parameters
accessTokenstring

setSystemDb()

Sets the internal client context to allow it to talk to the server’s internal system database

squashBranch(branchId, commitMsg)

Squash branch commits

Parameters
branchIdstringlocal identifier of the new branch
commitMsgstringTextual message describing the reason for the update
Returns
PromiseA promise that returns the call response object, or an Error if rejected.

updateDatabase(dbDoc)

Update a database in TerminusDB server

Parameters
dbDoctypedef.DbDocobject containing details about the database to be updated
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.updateDatabase({id: "mydb", label: "My Database", comment: "Testing"})

updateDocument(json, params, dbId, message, lastDataVersion, getDataVersion, compress, create)

Parameters
jsonobject
paramstypedef.DocParamsPutthe Put parameters {@link #typedef.DocParamsPut}
dbId*the database id
message*the update commit message
lastDataVersionstringthe last data version tracking id.
getDataVersionbooleanIf true the function will return object having result and dataVersion.
compressbooleanIf true, the function will create a new document if it doesn't exist.
createbooleanPerform an *upsert* which inserts if the document is not present (also works on nested documents)
Returns
PromiseA promise that returns the call response object or object having *result* and *dataVersion* object if ***getDataVersion*** parameter is true, or an Error if rejected.
Example: JavaScript
client.updateDocument(
{
 "@id": "Person",
   "@key": {
     "@type": "Random",
   },
   "@type": "Class",
   label: "xsd:string",
 },
{ graph_type: "schema" }
);


// Here we will pass true to show how to get dataVersion

    const response = await client.updateDocument(
      {
        "@id": "Person",
        "@key": {
          "@type": "Random",
        },
        "@type": "Class",
        label: "xsd:string",
      },
      { graph_type: "schema" },
      "",
      "",
      "",
      true
    );
console.log(response);

 // This will output:
 // {
 //   result: [ ...... ],
 //   dataVersion: 'branch:5fs681tlycnn6jh0ceiqcq4qs89pdfs'
 // }

 // Now we can use the data version we recieved as a response in previous
 // function call and used it is next function call as lastDataVersion

const response1 = await client.updateDocument(
      {
        "@id": "Person",
        "@key": {
          "@type": "Random",
        },
        "@type": "Class",
        label: "xsd:string",
      },
      { graph_type: "schema" },
      "",
      "",
      response.dataVersion
    );

 // update a document and create the linked document together
 // we are update the document "Person/Person01"
 // and create a new document {"@type": "Person","name": "child01"} at the same time
 const response1 = await client.updateDocument(
     {
      "@id": "Person/Person01",
      "@type": "Person",
      "name": "Person01"
      "children":[{"@type": "Person","name": "child01"}]
    },{create:true})

updateRemote(remoteName, remoteLocation)

Updates an existing remote connection

Parameters
remoteNamestringThe name of the remote to update
remoteLocationstringThe new URL for the remote repository
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.updateRemote("origin", "http://new.remote.server.com/org/db")

updateTriples(graphType, turtle, commitMsg)

Replace the contents of the specified graph with the passed triples encoded in the turtle (ttl) format

Parameters
graphTypestringtype of graph |instance|schema|inference|
turtlestringstring encoding triples in turtle (ttl) format
commitMsgstringTextual message describing the reason for the update
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
client.updateTriples("schema", "alt", turtle_string, "dumping triples to graph alt")

user()

Gets the current user object as returned by the connect capabilities response user has fields: [id, name, notes, author]

Returns
Object

userOrganization()

Returns
stringthe user organization name

userOrganizations(orgList)

Get/Set the list of the user's organizations (id, organization, label, comment).

Parameters
orgListarraya list of user's Organization
Returns
arraythe user Organizations list
Example: JavaScript
async funtion callGetUserOrganizations(){
     await client.getUserOrganizations()
     console.log(client.userOrganizations())
}

WOQL

The WOQL object is a wrapper around the WOQLQuery object

add_quad(subject, predicate, object, graphRef-)

Adds quads according to the pattern [S,P,O,G]

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphRef-typedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery

add_triple(subject, predicate, object)

Adds triples according to the the pattern [subject,predicate,object]

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery

added_quad(subject, predicate, object, graphRef-)

Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph) removed from the current commit

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphRef-typedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery

added_triple(subject, predicate, object)

Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object) added in the current layer

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery

all(subject, predicate, object, graphRef)

Generates a query that by default matches all triples in a graph - identical to star() except for order of arguments

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphReftypedef.GraphRefthe resource identifier of a graph possible value are schema/{main - myschema - *} | instance/{main - myschema - *} | inference/{main - myschema - *}
Returns
WOQLQuery- A WOQLQuery which contains the pattern matching expression all("mydoc") //will return every triple in the instance/main graph that has "doc:mydoc" as its subject

and(subqueries)

Logical conjunction of the contained queries - all queries must match or the entire clause fails

Parameters
subqueriesWOQLQueryA list of one or more woql queries to execute as a conjunction
Returns
WOQLQuery- A WOQLQuery object containing the conjunction of queries
Example: JavaScript
//find triples that are of type scm:Journey, and have
//a start_station Start, and that start_station is labeled Start_Label
let [Journey, Start, Start_Label] = vars("Journey", "Start", "Start_Label")
WOQL.and(
     WOQL.triple(Journey, "rdf:type", "@schema:Journey"),
     WOQL.triple(Journey, "start_station", Start),
     WOQL.triple(Start, "label", Start_Label))

as(source, target, type)

Imports the value identified by Source to a Target variable

Parameters
sourcestring|number|VarSource
targetstring|VarTarget
typestringtype to cast value to string|number etc...
Returns
WOQLQuery
Example: JavaScript
let [First_Var, Second_Var] = vars('First_Var', 'Second_Var')
WOQL.as("first var", First_Var, "string").as("second var", Second_Var)
WOQL.as(["first var", First_Var, "string"], ["second var", Second_Var])

boolean(bool)

Generates explicitly a JSON-LD literal boolean from the input

Parameters
boolbooleantrue | false
Returns
object- A JSON-LD literal boolean
Example: JavaScript
boolean(true)
//returns { "@type": "xsd:boolean", "@value": true }

client(client)

Use instead to run your query woqlclient.query('myWOQLQuery')

Parameters
clientWOQLClient
Returns
WOQLClient

comment(comment, subquery)

Adds a text comment to a query - can also be used to wrap any part of a query to turn it off

Parameters
commentstringtext comment
subqueryWOQLQueryquery that is "commented out"
Returns
WOQLQuery

concat(varList, resultVarName)

takes a variable number of string arguments and concatenates them into a single string

Parameters
varListarray|string|Vara variable representing a list or a list of variables or strings - variables can be embedded in the string if they do not contain spaces
resultVarNamestring|VarA variable or string containing the output string
Returns
WOQLQueryA WOQLQuery which contains the Concatenation pattern matching expression
Example: JavaScript
let [first_name, last_name, full_name] = vars("first_name", "last_name", "full_name")
concat([first_name, " ", last_name], full_name)

count(countVarName, subquery)

Creates a count of the results of the query

Parameters
countVarNamestring|number|Varvariable or integer count
subqueryWOQLQuery
Returns
WOQLQueryA WOQLQuery object containing the count sub Query
Example: JavaScript
let [count, Person] = vars("count", "Person")
WOQL.count(count).triple(Person, "rdf:type", "@schema:Person")

date(date)

Generates explicitly a JSON-LD literal date from the imput

Parameters
datestringany date format string (YYYY-MM-DD)
Returns
object- A JSON-LD literal date
Example: JavaScript
date("2022-10-02")
//returns { "@type": "xsd:date", "@value": "2022-10-02" }

datetime(datetime)

Generates explicitly a JSON-LD literal datetime from the imput

Parameters
datetimestringany datetime format string (YYYY-MM-DDThh-mm-ssZ)
Returns
object- A JSON-LD literal datetime
Example: JavaScript
datetime("2022-10-19T14:17:12Z")
//returns { "@type": "xsd:dateTime", "@value": "2022-10-19T14:17:12Z" }

delete_document(IRI)

Delete a document from the graph.

Parameters
IRIstringThe document id or a variable
Returns
objectWOQLQuery

delete_quad(subject, predicate, object, graphRef)

Deletes a single triple from the graph [Subject, Predicate, Object, Graph]

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphReftypedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery- A WOQLQuery which contains the Delete Quad Statement
Example: JavaScript
remove the class Person from the schema graph
WOQL.delete_quad("Person", "rdf:type", "sys:Class", "schema")

delete_triple(subject, predicate, object)

Deletes a single triple from the default graph of the database

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery- A WOQLQuery which contains the Triple Deletion statement
Example: JavaScript
delete_triple("john", "age", 42)

distinct(varNames)

Filter the query to return only results that are distinct in the given variables

Parameters
varNamesstring|Varthese variables are guaranteed to be unique as a tuple
Returns
WOQLQuery

div(args)

Division - integer division - args are divided left to right

Parameters
argsstring|number|Varnumbers for division
Returns
WOQLQueryA WOQLQuery which contains the division expression
Example: JavaScript
let [result] = vars("result")
evaluate(div(10, 3), result)
//result contains 3

divide(args)

Divides numbers N1...Nn by each other left, to right precedence

Parameters
argsstring|number|Varnumbers to tbe divided
Returns
WOQLQueryA WOQLQuery which contains the division expression let [result] = vars("result") evaluate(divide(times(10, minus(2.1, plus(0.2, 1))), 10), result) //result contains 0.9000000000000001

doc(object)

Produces an encoded form of a document that can be used by a WOQL operation such as `WOQL.insert_document`.

Parameters
objectobjectDocument to encode
Returns
objectThe encoded document
Example: JavaScript
const doc = WOQL.doc({ "@type": "Person", name: "Newperson" })

dot(document, field, value)

Extract the value of a key in a bound document.

Parameters
documentstring|VarDocument which is being accessed.
fieldstring|VarThe field from which the document which is being accessed.
valuestring|VarThe value for the document and field.
Returns
WOQLQueryA WOQLQuery which contains the a dot Statement

emerge(auto_eval)

query module allow you to use WOQL words as top level functions

Parameters
auto_eval*

eq(varName, varValue)

Matches if a is equal to b

Parameters
varNamestring|Varliteral, variable or id
varValuestring|Varliteral, variable or id
Returns
WOQLQuery

eval(arithExp, resultVarName)

Evaluates the passed arithmetic expression and generates or matches the result value

Parameters
arithExpobject|WOQLQuery|stringA WOQL query containing a valid WOQL Arithmetic Expression, which is evaluated by the function
resultVarNamestring|number|VarEither a variable, in which the result of the expression will be stored, or a numeric literal which will be used as a test of result of the evaluated expression
Returns
WOQLQueryA WOQLQuery which contains the Arithmetic function
Example: JavaScript
let [result] = vars("result")
eval(plus(2, minus(3, 1)), result)

evaluate(arithExp, resultVarName)

Evaluates the passed arithmetic expression and generates or matches the result value

Parameters
arithExpobject|WOQLQuery|stringA WOQL query containing a valid WOQL Arithmetic Expression, which is evaluated by the function
resultVarNamestring|number|VarEither a variable, in which the result of the expression will be stored, or a numeric literal which will be used as a test of result of the evaluated expression
Returns
WOQLQueryA WOQLQuery which contains the Arithmetic function
Example: JavaScript
let [result] = vars("result")
evaluate(plus(2, minus(3, 1)), result)

exp(varNum, expNum)

Exponent - raises varNum01 to the power of varNum02

Parameters
varNumstring|number|Vara variable or numeric containing the number to be raised to the power of the second number
expNumnumbera variable or numeric containing the exponent
Returns
WOQLQueryA WOQLQuery which contains the exponent expression
Example: JavaScript
let [result] = vars("result")
evaluate(exp(3, 2), result)
//result contains 9

floor(varNum)

Generates the nearest lower integer to the passed number

Parameters
varNumstring|number|VarVariable or numeric containing the number to be floored
Returns
WOQLQueryA WOQLQuery which contains the floor expression
Example: JavaScript
let [result] = vars("result")
evaluate(divide(floor(times(10, minus(2.1, plus(0.2, 1)))), 10), result)
//result contains 0.9 - floating point error removed

from(graphRef-, query)

Specifies the database URL that will be the default database for the enclosed query

Parameters
graphRef-typedef.GraphRefA valid graph resource identifier string
queryWOQLQueryThe query
Returns
WOQLQueryA WOQLQuery object containing the from expression

get(asvars, queryResource)

Use the document inteface to import documents

Parameters
asvarsVars|array.<Var>an array of AsVar variable mappings (see as for format below)
queryResourceWOQLQueryan external resource (remote, file, post) to query
Returns
WOQLQueryA WOQLQuery which contains the get expression
Example: JavaScript
let [a, b] = vars("a", "b")
get(as("a", a).as("b", b)).remote("http://my.url.com/x.csv")
//copies the values from column headed "a" into a variable a and from column
//"b" into a variable b from remote CSV

graph(graphRef)

Sets the graph resource ID that will be used for subsequent chained function calls

Parameters
graphReftypedef.GraphRefResource String identifying the graph which will be used for subsequent chained schema calls
Returns
WOQLQueryA WOQLQuery which contains the partial Graph pattern matching expression
Example: JavaScript
WOQL.graph("schema")
//equivalent to add_quad("MyClass", "label", "My Class Label", "schema/main")

greater(varNum01, varNum02)

Compares the value of v1 against v2 and returns true if v1 is greater than v2

Parameters
varNum01string|number|Vara variable or numeric containing the number to be compared
varNum02string|number|Vara variable or numeric containing the second comporator
Returns
WOQLQueryA WOQLQuery which contains the comparison expression
Example: JavaScript
let [result] = vars("result")
greater(1.2, 1.1).eq(result, literal(true, "boolean"))
//result contains true

group_by(varList, patternVars, resultVarName, subquery)

Groups the results of the contained subquery on the basis of identical values for Groupvars, extracts the patterns defined in PatternVars and stores the results in GroupedVar

Parameters
varListarray|string|VarEither a single variable or an array of variables
patternVarsarray|string|VarEither a single variable or an array of variables
resultVarNamestring|Varoutput variable name
subqueryWOQLQueryThe query whose results will be grouped
Returns
WOQLQueryA WOQLQuery which contains the grouping expression
Example: JavaScript
//subquery is an argument or a chained query
let [age, last_name, first_name, age_group, person] = vars("age", "last name", "first name",
"age group", "person")
group_by(age, [last_name, first_name], age_group)
  .triple(person, "first_name", first_name)
  .triple(person, "last_name", last_name)
  .triple(person, "age", age)

idgen(prefix, inputVarList, resultVarName)

Generate a new IRI from the prefix and concatention of the variables

Parameters
prefixstringA prefix for the IRI - typically formed of the doc prefix and the classtype of the entity (“doc:Person”)
inputVarListarray|string|VarAn array of variables and / or strings from which the unique hash will be generated
resultVarNamestring|VarVariable in which the unique ID is stored
Returns
WOQLQueryA WOQLQuery object containing the ID generating function
Example: JavaScript
let [newid] = vars("newid")
idgen("doc:Person", ["John", "Smith"], newid)

idgen_random(prefix, resultVarName)

Generates a random ID with a specified prefix

Parameters
prefixstringprefix for the generated ID
resultVarNamestringvariable that stores the generated ID
Returns
WOQLQueryA WOQLQuery object containing the random ID generation function
Example: JavaScript
let [newid] = vars("newid")
idgen_random("Person/", newid)

immediately(subquery)

Runs the query without backtracking on side-effects

Parameters
subquerystring|WOQLQueryWOQL Query objects
Returns
WOQLQueryA WOQLQuery object containing the immediately sub Query

insert(classId, classType, graphRef)

Inserts a single triple into the database declaring the Node to have type Type, optionally into the specified graph

Parameters
classIdstring|VarIRI string or variable containing the IRI of the node to be inserted
classTypestring|VarIRI string or variable containing the IRI of the type of the node (class/document name)
graphReftypedef.GraphRefOptional Graph resource identifier
Returns
WOQLQueryA WOQLQuery which contains the insert expression
Example: JavaScript
insert("mydoc", "MyType")
//equivalent to add_triple("mydoc", "rdf:type", "@schema:MyType")

insert_document(docjson, IRI)

Insert a document in the graph.

Parameters
docjsonobjectThe document to insert. Must either have an '@id' or have a class specified key.
IRIstringAn optional identifier specifying the document location.
Returns
objectWOQLQuery
Example: JavaScript
const res = await client.query(
   WOQL.insert_document(WOQL.doc({ "@type" : "Person", "label": "John" }))
)

into(graphRef-, subquery)

Specifies the graph resource to write the contained query into

Parameters
graphRef-typedef.GraphRefA valid graph resource identifier string
subqueryWOQLQueryThe query which will be written into the graph
Returns
WOQLQueryA WOQLQuery which will be written into the graph in question
Example: JavaScript
//Subq is an argument or a chained query
using("admin/minecraft").into("instance/main").add_triple("a", "rdf:type", "@schema:X")
//writes a single tripe (doc:a, rdf:type, scm:X) into the main instance graph

iri(val)

Explicitly sets a value to be an IRI - avoiding automatic type marshalling

Parameters
valstringstring which will be treated as an IRI
Returns
object- A JSON-LD IRI value

isa(instanceIRI, classId)

Tests whether a given instance IRI has type Class, according to the current state of the DB

Parameters
instanceIRIstring|VarA string IRI or a variable that identify the class instance
classIdstring|VarA Class IRI or a variable
Returns
WOQLQueryA WOQLQuery object containing the type test
Example: JavaScript
let [subject] = vars("subject")
isa(subject, "Person")

join(varList, glue, resultVarName)

Joins a list variable together (Input) into a string variable (Output) by glueing the strings together with Glue

Parameters
varListstring|array|Vara variable representing a list or a list of strings and / or variables
gluestring|VarA variable (v:glue) or (glue) string representing the characters to put in between the joined strings in input
resultVarNamestring|VarA variable or string containing the output string
Returns
WOQLQueryA WOQLQuery which contains the Join pattern matching expression
Example: JavaScript
let [sentence] = vars("sentence")
join(["joe", "has", "a", "hat", " ", sentence)

json(JSON_LD)

Generates a WOQLQuery object from the passed WOQL JSON - if an argument is passed, the query object is created from it, if none is passed, the current state is returned as a JSON-LD

Parameters
JSON_LDobjectJSON-LD woql document encoding a query
Returns
WOQLQuery|objecteither a JSON-LD or a WOQLQuery object json version of query for passing to api

length(inputVarList, resultVarName)

Calculates the length of the list in va and stores it in vb

Parameters
inputVarListstring|arrayEither a variable representing a list or a list of variables or literals
resultVarNamestring|VarA variable in which the length of the list is stored or the length of the list as a non-negative integer
Returns
WOQLQueryA WOQLQuery which contains the Length pattern matching expression
Example: JavaScript
let [count] = vars("count")
length(["john", "joe", "frank"], count)

less(varNum01, varNum02)

Compares the value of v1 against v2 and returns true if v1 is less than v2

Parameters
varNum01string|number|Vara variable or numeric containing the number to be compared
varNum02string|number|Vara variable or numeric containing the second comporator
Returns
WOQLQueryA WOQLQuery which contains the comparison expression
Example: JavaScript
let [result] = vars("result")
less(1, 1.1).eq(result, literal(true, "boolean"))
//result contains true

lib()

get the predefined library query [WOQLLibrary](/api/woqlLibrary.js?id=WOQLLibrary)

Returns
WOQLQueryWOQLQuery object
Example: JavaScript
//get commits older than the specified commit id
const query = WOQL.lib().previousCommits('m8vpxewh2aovfauebfkbzwmj4qwr5lb')

//return the commits of a specific branch starting from the head
//you can add the limit (how many results to return.) and the start point
//if a timestamp is given, gets the commits before the specified timestamp
//WOQL.lib().commits(branch='main',limit=0,start=0,timestamp=0)

const query = WOQL.lib().commits('main',10,2,1630683082.9278786)

//return the branches list with the timestamp and commits id
const query = WOQL.lib().branches()

like(stringA, stringB, distance)

Generates a string Leverstein distance measure between stringA and stringB

Parameters
stringAstring|Varstring literal or variable representing a string to be compared
stringBstring|Varstring literal or variable representing the other string to be compared
distancenumber|string|Varvariable representing the distance between the variables
Returns
WOQLQueryA WOQLQuery which contains the Like pattern matching expression
Example: JavaScript
let [dist] = vars('dist')
like("hello", "hallo", dist)
//dist contains 0.7265420560747664

limit(limit, subquery)

Specifies a maximum number of results that will be returned from the subquery

Parameters
limitnumber|stringA variable that refers to an non-negative integer or a non-negative integer
subqueryWOQLQueryA subquery whose results will be limited
Returns
WOQLQueryA WOQLQuery whose results will be returned starting from the specified offset
Example: JavaScript
let [a, b, c] = vars("a", "b", "c")
limit(100).triple(a, b, c)
//subquery is an argument or a chained query
limit(100,triple(a, b, c))

literal(val, type)

Generates explicitly a JSON-LD string literal from the input

Parameters
valstringany literal type
typestringan xsd or xdd type
Returns
object- A JSON-LD literal
Example: JavaScript
literal(1, "nonNegativeInteger")
//returns { "@type": "xsd:nonNegativeInteger", "@value": 1 }

lower(inputVarName, resultVarName)

Changes a string to lower-case

Parameters
inputVarNamestring|Varstring or variable representing the non-lowercased string
resultVarNamestring|Varvariable that stores the lowercased string output
Returns
WOQLQueryA WOQLQuery which contains the Lower case pattern matching expression
Example: JavaScript
let [lower] = var("l")
lower("aBCe", lower)
//lower contains "abce"

member(element, list)

Matches if List includes Element

Parameters
elementstring|object|VarEither a variable, IRI or any simple datatype
liststring|array|VarList ([string, literal] or string*) Either a variable representing a list or a list of variables or literals
Returns
WOQLQueryA WOQLQuery which contains the List inclusion pattern matching expression
Example: JavaScript
let [name] = vars("name")
member(name, ["john", "joe", "frank"])

minus(args)

Subtracts Numbers N1..Nn

Parameters
argsstring|number|Varvariable or numeric containing the value that will be subtracted from
Returns
WOQLQueryA WOQLQuery which contains the subtraction expression
Example: JavaScript
let [result] = vars("result")
evaluate(minus(2.1, plus(0.2, 1)), result)

node(nodeid, chainType)

Specifies the identity of a node that can then be used in subsequent builder functions. Note that node() requires subsequent chained functions to complete the triples / quads that it produces - by itself it only generates the subject.

Parameters
nodeidstring|VarThe IRI of a node or a variable containing an IRI which will be the subject of the builder functions
chainTypetypedef.FuntionTypeOptional type of builder function to build (default is triple)
Returns
WOQLQuery- A WOQLQuery which contains the partial Node pattern matching expression
Example: JavaScript
node("mydoc").label("my label")
//equivalent to triple("mydoc", "label", "my label")

not(subquery)

Logical negation of the contained subquery - if the subquery matches, the query will fail to match

Parameters
subquerystring|WOQLQueryA subquery which will be negated
Returns
WOQLQueryA WOQLQuery object containing the negated sub Query
Example: JavaScript
let [subject, label] = vars("subject", "label")
not().triple(subject, 'label', label)

nuke(graphRef)

Deletes all triples in the passed graph (defaults to instance/main)

Parameters
graphReftypedef.GraphRefResource String identifying the graph from which all triples will be removed
Returns
WOQLQuery- A WOQLQuery which contains the deletion expression
Example: JavaScript
nuke("schema/main")
//will delete everything from the schema/main graph

once(subquery)

Results in one solution of the subqueries

Parameters
subquerystring|WOQLQueryWOQL Query objects
Returns
WOQLQueryA WOQLQuery object containing the once sub Query

opt(subquery)

Specifies that the Subquery is optional - if it does not match the query will not fail

Parameters
subqueryWOQLQueryA subquery which will be optionally matched
Returns
WOQLQueryA WOQLQuery object containing the optional sub Query
Example: JavaScript
let [subject] = vars("subject")
opt(triple(subject, 'label', "A"))
//Subq is an argument or a chained query
opt().triple(subject, 'label', "A")

or(subqueries)

Creates a logical OR of the arguments

Parameters
subqueriesWOQLQueryA list of one or more woql queries to execute as alternatives
Returns
WOQLQuery- A WOQLQuery object containing the logical Or of the subqueries
Example: JavaScript
let [Subject] = vars("Subject")
or(
  triple(Subject, 'label', "A"),
  triple(Subject, "label", "a")
 )

order_by(varNames)

Orders the results of the contained subquery by a precedence list of variables

Parameters
varNamesstring|Var|arrayA sequence of variables, by which to order the results, each optionally followed by either “asc” or “desc” to represent order as a list, by default it will sort the variable in ascending order
Returns
WOQLQueryA WOQLQuery which contains the ordering expression
Example: JavaScript
let [A, B, C] = vars("A", "B", "C")
WOQL.order_by(A, [B, "asc"], [C, "desc"]).triple(A, B, C);

pad(inputVarName, pad, len, resultVarName)

Pads out the string input to be exactly len long by appending the pad character pad to form output

Parameters
inputVarNamestring|VarThe input string or variable in unpadded state
padstring|VarThe characters to use to pad the string or a variable representing them
lennumber|string|VarThe variable or integer value representing the length of the output string
resultVarNamestring|Varstores output
Returns
WOQLQueryA WOQLQuery which contains the Pad pattern matching expression
Example: JavaScript
let [fixed] = vars("fixed length")
pad("joe", " ", 8, fixed)
//fixed contains "joe     "

path(subject, pattern, object, resultVarName)

Performs a path regular expression match on the graph

Parameters
subjectstring|VarAn IRI or variable that refers to an IRI representing the subject, i.e. the starting point of the path
patternstring(string) - A path regular expression describing a pattern through multiple edges of the graph (see: https://terminusdb.com/docs/path-query-reference-guide)
objectstring|VarAn IRI or variable that refers to an IRI representing the object, i.e. ending point of the path
resultVarNamestring|VarA variable in which the actual paths traversed will be stored
Returns
WOQLQuery- A WOQLQuery which contains the path regular expression matching expression
Example: JavaScript
let [person, grand_uncle, lineage] = vars("person", "grand uncle", "lineage")
path(person, "((father|mother) {2,2}), brother)", grand_uncle, lineage)

plus(args)

Adds the numbers together

Parameters
argsstring|number|Vara variable or numeric containing the values to add
Returns
WOQLQueryA WOQLQuery which contains the addition expression
Example: JavaScript
let [result] = vars("result")
evaluate(plus(2, plus(3, 1)), result)

post(url, formatObj, source)

Identifies a resource as a local path on the client, to be sent to the server through a HTTP POST request, with the format defined through the options

Parameters
urlstringThe Path on the server at which the file resource can be accessed
formatObjtypedef.DataFormatObjimput options, optional
sourcestringIt defines the source of the file, it can be 'url','post'
Returns
WOQLQueryA WOQLQuery which contains the Post resource identifier
Example: JavaScript
post("/.../.../", {type:'csv'})

put(varsToExp, query, fileResource)

Use the document inteface to import documents

Parameters
varsToExpVars|array.<Var>an array of AsVar variable mappings (see as for format below)
queryWOQLQueryThe query which will be executed to produce the results
fileResourcestringan file resource local to the server
Returns
WOQLQueryA WOQLQuery which contains the put expression

quad(subject, predicate, object, graphRef)

Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph)

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphReftypedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery

query()

Generates an empty WOQLQuery object

Returns
WOQLQuery
Example: JavaScript
let q = query()
//then q.triple(1, 1) ...

random_idgen(prefix, resultVarName)

Backward-compatible alias for idgen_random

Parameters
prefixstringprefix for the generated ID
resultVarNamestringvariable that stores the generated ID
Returns
WOQLQueryA WOQLQuery object containing the random ID generation function

re(pattern, inputVarName, resultVarList)

Matches the regular expression defined in Patern against the Test string, to produce the matched patterns in Matches

Parameters
patternstringstring or variable using normal PCRE regular expression syntax with the exception that special characters have to be escaped twice (to enable transport in JSONLD)
inputVarNamestring|Varstring or variable containing the string to be tested for patterns with the regex
resultVarListstring|array|object|Varvariable representing the list of matches or a list of strings or variables
Returns
WOQLQueryA WOQLQuery which contains the Regular Expression pattern matching expression
Example: JavaScript
let [All, Sub] = vars("All", "Sub")
WOQL.re("h(.).*", "hello", [All, Sub])
//e contains 'e', llo contains 'llo'
//p is a regex pattern (.*) using normal regular expression syntax, the only unusual
thing is that special characters have to be escaped twice, s is the string to be matched
and m is a list of matches:

read_document(IRI, output)

Read a node identified by an IRI as a JSON-LD document

Parameters
IRIstringThe document id or a variable to read
outputstringVariable which will be bound to the document.
Returns
objectWOQLQuery
Example: JavaScript
let [person] = vars("Person")
const query = WOQL.read_document(
     "Person/0b4feda109d9d13c9da809090b342ad9e4d8185545ce05f7cd20b97fe458f547",
    person
);
const res =  await client.query(query);

read_object()

Use {@link #read_document|read_document} instead.

remote(remoteObj, formatObj)

Identifies a remote resource by URL and specifies the format of the resource through the options

Parameters
remoteObjobjectThe URL at which the remote resource can be accessed
formatObjtypedef.DataFormatObjThe format of the resource data {}
Returns
WOQLQueryA WOQLQuery which contains the remote resource identifier
Example: JavaScript
remote({url:"http://url.of.resource"}, {type: "csv"})

removed_quad(subject, predicate, object, graphRef-)

Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph) removed from the current commit

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphRef-typedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery

removed_triple(subject, predicate, object)

Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object) added in the current commit

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery

select(varNames)

Parameters
varNamesstring|Varonly these variables are returned
Returns
WOQLQuery
Example: JavaScript
let [a, b, c] = vars("a", "b", "c")
WOQL.select(a, triple(a, b, c))
Filters the query so that only the variables included in [V1...Vn] are returned in the bindings

size(resourceId, resultVarName)

Calculates the size in bytes of the contents of the resource identified in ResourceID

Parameters
resourceIdstring|VarA valid resource identifier string (can refer to any graph / branch / commit / db)
resultVarNamestring|VarThe variable name
Example: JavaScript
let [varSize] = vars("varSize")
size("admin/minecraft/local/branch/main/instance/main", varSize)
//returns the number of bytes in the main instance graph on the main branch

slice(inputList, resultVarName, start, end)

Extracts a contiguous subsequence from a list, following JavaScript's slice() semantics

Parameters
inputListstring|array|VarEither a variable representing a list or a list of variables or literals
resultVarNamestring|VarA variable in which the sliced list is stored
startnumber|string|VarThe start index (0-based, supports negative indices)
endnumber|string|VarThe end index (exclusive, optional - defaults to list length)
Returns
WOQLQueryA WOQLQuery which contains the Slice pattern matching expression
Example: JavaScript
let [result] = vars("result")
slice(["a", "b", "c", "d"], result, 1, 3)  // result = ["b", "c"]
slice(["a", "b", "c", "d"], result, -2)    // result = ["c", "d"]

split(inputVarName, separator, resultVarName)

Splits a string (Input) into a list strings (Output) by removing separator

Parameters
inputVarNamestring|VarA string or variable representing the unsplit string
separatorstring|VarA string or variable containing a sequence of charatcters to use as a separator
resultVarNamestring|Varvariable that stores output list
Returns
WOQLQueryA WOQLQuery which contains the Split pattern matching expression
Example: JavaScript
let [words] = vars("words")
split("joe has a hat", " ", words)

star(graph, subject, predicate, object)

Generates a query that by default matches all triples in a graph identified by "graph" or in all the current terminusDB's graph

Parameters
graphstring|booleanfalse or the resource identifier of a graph possible value are schema/{main - myschema - *} | instance/{main - myschema - *} | inference/{main - myschema - *}
subjectstring|VarThe IRI of a triple’s subject or a variable, default value "v:Subject"
predicatestring|VarThe IRI of a property or a variable, default value "v:Predicate"
objectstring|VarThe IRI of a node or a variable, or a literal, default value "v:Object"
Returns
WOQLQueryA WOQLQuery which contains the pattern matching expression
Example: JavaScript
star("schema/main")
//will return every triple in schema/main graph

start(start, subquery)

Specifies an offset position in the results to start listing results from

Parameters
startnumber|string|VarA variable that refers to an interger or an integer literal
subqueryWOQLQueryWOQL Query object, you can pass a subquery as an argument or a chained query
Returns
WOQLQueryA WOQLQuery whose results will be returned starting from the specified offset
Example: JavaScript
let [a, b, c] = vars("a", "b", "c")
start(100).triple(a, b, c)

string(val)

Generates explicitly a JSON-LD string literal from the input

Parameters
valstring|boolean|numberany primitive literal type
Returns
object- A JSON-LD string literal
Example: JavaScript
string(1)
//returns { "@type": "xsd:string", "@value": "1" }

sub(classA, classB)

Returns true if ClassA subsumes ClassB, according to the current DB schema

Parameters
classAstringClassA
classBstringClassB
Returns
booleanWOQLQuery

substr(string, before, length, after, substring)

Substring of string

Parameters
stringstring|VarString or variable
beforenumber|Varinteger or variable (characters from start to begin)
lengthnumber|Varinteger or variable (length of substring)
afternumber|Varinteger or variable (number of characters after substring)
substringstring|VarString or variable
Returns
WOQLQuery
Example: JavaScript
let [after, result] = vars("after", "result")
substr("joe", 1, 2, after, result)
//result is "oe", after is 2

sum(subquery, total)

computes the sum of the List of values passed. In contrast to other arithmetic functions, sum self-evaluates - it does not have to be passed to evaluate()

Parameters
subqueryWOQLQuerya subquery or ([string or numeric]) - a list variable, or a list of variables or numeric literals
totalstring|Varthe variable name with the sum result of the values in List
Returns
WOQLQuery- A WOQLQuery which contains the Sum expression
Example: JavaScript
let [total] = vars("total")
sum([2, 3, 4, 5], total)

times(args)

Multiplies numbers N1...Nn together

Parameters
argsstring|number|Vara variable or numeric containing the value
Returns
WOQLQueryA WOQLQuery which contains the multiplication expression
Example: JavaScript
let [result] = vars("result")
evaluate(times(10, minus(2.1, plus(0.2, 1))), result)
 //result contains 9.000000000000002y

trim(inputStr, resultVarName)

Remove whitespace from both sides of a string:

Parameters
inputStrstring|VarA string or variable containing the untrimmed version of the string
resultVarNamestring|VarA string or variable containing the trimmed version of the string
Returns
WOQLQueryA WOQLQuery which contains the Trim pattern matching expression
Example: JavaScript
let [trimmed] = vars("trimmed")
trim("hello   ", trimmed)
//trimmed contains "hello"

triple(subject, predicate, object)

Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object)

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery

triple_count(resourceId, tripleCount)

Calculates the number of triples of the contents of the resource identified in ResourceID

Parameters
resourceIdstring|VarA valid resource identifier string (can refer to any graph / branch / commit / db)
tripleCountstring|number|VarAn integer literal with the size in bytes or a variable containing that integer
Returns
WOQLQueryA WOQLQuery which contains the size expression
Example: JavaScript
let [count] = vars("count")
triple_count("admin/minecraft/local/_commits", count)
//returns the number of bytes in the local commit graph

true()

A function that always matches, always returns true

Returns
WOQLQueryA WOQLQuery object containing the true value that will match any pattern
Example: JavaScript
when(true()).triple("a", "b", "c")

type_of(elementId, elementType)

Returns true if 'elementId' is of type 'elementType', according to the current DB schema

Parameters
elementIdstring|Varthe id of a schema graph element
elementTypestring|Varthe element type
Returns
WOQLQueryA WOQLQuery object containing the type_of pattern matching rule

typecast(varName, varType, resultVarName)

Casts the value of Input to a new value of type Type and stores the result in CastVar

Parameters
varNamestring|number|object|VarEither a single variable or a literal of any basic type
varTypestring|VarEither a variable or a basic datatype (xsd / xdd)
resultVarNamestring|Varsave the return variable
Returns
WOQLQueryA WOQLQuery which contains the casting expression
Example: JavaScript
let [time] = vars("time")
cast("22/3/98", "xsd:dateTime", time)

unique(prefix, inputVarList, resultVarName)

Generate a new IRI from the prefix and a hash of the variables which will be unique for any given combination of variables

Parameters
prefixstringA prefix for the IRI - typically formed of the doc prefix and the classtype of the entity (“doc:Person”)
inputVarListarray|string|VarAn array of variables and / or strings from which the unique hash will be generated
resultVarNamestring|VarVariable in which the unique ID is stored
Returns
WOQLQueryA WOQLQuery object containing the unique ID generating function
Example: JavaScript
let [newid] = vars("newid")
unique("doc:Person", ["John", "Smith"], newid)

update_document(docjson, IRI)

Update a document identified by an IRI

Parameters
docjsonobjectThe document to update. Must either have an '@id' or have a class specified key.
IRIstringAn optional identifier specifying the document location.
Returns
objectWOQLQuery

update_quad(subject, predicate, newObject, graphRef)

Update a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph)

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
newObjectstring|VarThe value to update or a literal
graphReftypedef.GraphRefA valid graph resource identifier string
Returns
WOQLQueryA WOQLQuery which contains the a Update Quad Statement

update_triple(subject, predicate, newObjValue, oldObjValue)

Update a pattern matching rule for the triple (Subject, Predicate, oldObjValue) with the new one (Subject, Predicate, newObjValue)

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
newObjValuestring|VarThe value to update or a literal
oldObjValuestring|VarThe old value of the object
Returns
WOQLQueryA WOQLQuery which contains the a Update Triple Statement

upper(inputVarName, resultVarName)

Changes a string to upper-case

Parameters
inputVarNamestring|Varstring or variable representing the uncapitalized string
resultVarNamestring|Varvariable that stores the capitalized string output
Returns
WOQLQueryA WOQLQuery which contains the Upper case pattern matching expression
Example: JavaScript
let [allcaps] = vars("allcaps")
upper("aBCe", allcaps)
//upper contains "ABCE"

using(refPath, subquery)

Query running against any specific commit Id

Parameters
refPathstringpath to specific reference Id or commit Id
subqueryWOQLQuerysubquery for the specific commit point
Returns
WOQLQuery
Example: JavaScript
let [a, b, c] = vars("a", "b", "c")
WOQL.using("userName/dbName/local/commit|branch/commitID").triple(a, b, c)

value(subject, predicate, objValue)

Creates a pattern matching rule for a triple [Subject, Predicate, Object] add extra information about the type of the value object

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objValuestring|number|boolean|Varan specific value
Returns
WOQLQueryA WOQLQuery which contains the a quad or a triple Statement

vars(varNames)

Generates javascript variables for use as WOQL variables within a query

Parameters
varNamesstring
Returns
Array.<Var>an array of javascript variables which can be dereferenced using the array destructuring operation
Example: JavaScript
const [a, b, c] = WOQL.vars("a", "b", "c")
//a, b, c are javascript variables which can be used as WOQL variables in subsequent queries

Vars(varNames)

Parameters
varNamesstring
Returns
object.<Var>
Example: JavaScript
const v = WOQL.Vars('var01', 'var02', 'var03');
triple(v.var01, v.var02, v.var03)

vars_unique(varNames)

Generates unique javascript variables for use as WOQL variables within a query

Parameters
varNamesstring
Returns
Array.<Var>an array of javascript variables which can be dereferenced using the array destructuring operation
Example: JavaScript
const [a, b, c] = WOQL.vars("a", "b", "c")
//a, b, c are javascript variables that are unique WOQL variables

vars_unique_reset_start(start)

Sets the unique variable counter to a specific value This is particularly useful together with select() for locally scoped variables

Parameters
startnumberstarting value

VarsUnique(varNames)

Produces variables with unique names by appending an incrementing counter to each variable name. This is particularly useful together with select() for locally scoped variables

Parameters
varNamesstring
Returns
object.<Var>
Example: JavaScript
// Creates variables like "a_4", "b_5" - unique even with same input names
const v = WOQL.VarsUnique('var01', 'var02', 'var03');
triple(v.var01, v.var02, v.var03) // locally scoped

WOQLLibrary

Library Functions to manage the commits graph

branches()

General Pattern 4: Retrieves Branches, Their ID, Head Commit ID, Head Commit Time (if present, new branches have no commits)

commits(branch, limit, start, timestamp)

get all the commits of a specific branch if a timestamp is given, gets all the commits before the specified timestamp

Parameters
branchstringthe branch name
limitnumberthe max number of result
startnumberthe start of the pagination
timestampnumberUnix timestamp in seconds

first_commit()

Finds the id of the very first commit in a database's history This is useful for finding information about when, by who and why the database was created The first commit is the only commit in the database that does not have a parent commit

previousCommits(commit_id, limit)

get commits older than the specified commit id

Parameters
commit_idstringthe commit id
limitnumberthe max number of result

AccessControl

The AccessControl is a driver to work with

accessRequestsList(orgName)

-- TerminusX API -- Get all the access request list for a specify organization

Parameters
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.accessRequestsList().then(result=>{
 console.log(result)
})

createOrganization(orgName)

-- TerminusDB API --- This end point works in basic authentication, admin user Create an organization

Parameters
orgNamestringThe organization name to create
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.createOrganization("my_org_name").then(result=>{
     console.log(result)
})

createOrganizationRemote(orgName)

-- TerminusX API --- IMPORTANT This does not work with the API-TOKEN. Create an organization

Parameters
orgNamestringThe organization name to create
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.createOrganization("my_org_name").then(result=>{
     console.log(result)
})

createRole(name, actions)

--TerminusDB API --- basic authentication, admin user. Create a new role in the system database.

Parameters
namestringThe role name.
actionstypedef.RolesActionsA list of actions
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.createRole("Reader",[ACTIONS.INSTANCE_READ_ACCESS]).then(result=>{
 console.log(result)
})

createUser(name, password)

-- TerminusdDB API --- basic Authentication, admin user. Add the user into the system database

Parameters
namestringthe user name
passwordstringyou need the password for basic authentication
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.deleteUser(userId).then(result=>{
 console.log(result)
})

createUserRole(userId, scope, role, orgName)

-- TerminusX API -- Create a user's a role for a resource (organization/database)

Parameters
userIdstringThe user's id.
scopestringThe resource name/id.
rolestringThe user role to be assigned.
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
const dbId = "UserDatabase/acfcc2db02b83792sssb15239ccdf586fc5b176846ffe4878b1aea6a36c8f"
accessControl.assignUserRole('User/auth0%7C61790e11a3966d006906596a',dbId,
"Role/collaborator").then(result=>{
     console.log(result)

})

customHeaders(customHeaders)

add extra headers to your request

Parameters
customHeadersobject
Returns
object

deleteAccessRequest(orgName)

-- TerminusX API -- Delete an access request to join your team, only an admin user can delete it

Parameters
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.deleteAccessRequest("djjdshhsuuwewueueuiHYHYYW.......").then(result=>{
 console.log(result)
})

deleteOrganization(orgName)

-- TerminusDB API --- Delete an Organization

Parameters
orgNamestringThe organization name to delete
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.deleteOrganization("my_org_name").then(result=>{
     console.log(result)
})

deleteOrgInvite(inviteId, orgName)

-- TerminusX API --- Delete an invitation

Parameters
inviteIdstringThe invite id to delete.
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
const fullInviteId="Organization/my_team_name/invitations/Invitation/7ad0c9eb82b6175bcda9
c0dfc2ac51161ef5ba7cb0988d992c4bce82b3fa5d25"
accessControl.deleteOrgInvite(fullInviteId).then(result=>{
     console.log(result)
})

deleteRole(name)

-- TerminusdDB API --- basic Authentication, admin user. Delete role in the system database, (this api is enabled only in the local installation)

Parameters
namestringThe role name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.deleteRole("Reader").then(result=>{
 console.log(result)
})

deleteUser(userId)

-- TerminusdDB API --- basic Authentication, admin user. Remove the user from the system database.

Parameters
userIdstringthe document user id
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.deleteUser(userId).then(result=>{
 console.log(result)
})

getAccessRoles()

--TerminusX and TerminusDB API --- Get all the system database roles types.

Returns
PromiseA promise that returns the call response object, or an Error if rejected.

getAllOrganizations()

-- TerminusDB API --- This end point works in basic authentication, admin user Get list of organizations

Returns
PromiseA promise that returns the call response object, or an Error if rejected.

getAllUsers()

-- TerminusdDB API --- basic Authentication, admin user. Return the list of all the users (this api is enabled only in the local installation)

Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.getAllUsers().then(result=>{
 console.log(result)
})

getAPIUrl(cloudAPIUrl)

Get a API url from cloudAPIUrl

Parameters
cloudAPIUrlstringThe base url for cloud
Returns
stringapiUrl

getDatabaseRolesOfUser(userId, orgName)

-- TerminusX API -- Get the user's role for every databases under the organization

Parameters
userIdstringThe user's id.
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.getDatabaseRolesOfUser('User/auth0%7C61790e366377Yu6596a').then(result=>{
     console.log(result)
})

//this is a capabilities list of databases and roles
//[ {capability: "Capability/b395e8523d509dec6b33aefc9baed3b2e2bfadbd4c79d4ff9b20dce2b14e2edc"
//if there is an id we have a user specific capabality for this database
   // name: {@type: "xsd:string", @value: "profiles_test"}
   // role: "Role/dataUpdater"
   // scope: "UserDatabase/7ebdfae5a02bc7e8f6d79sjjjsa4e179b1df9d4576a3b1d2e5ff3b4859"
   // user: "User/auth0%7C61790e11a3966d006906596a"},

//{ capability: null
// if the capability id is null the user level of access for this database is the
same of the team
  //name: {@type: "xsd:string", @value: "Collab002"}
  //role: "Role/dataReader"
  // scope: "UserDatabase/acfcc2db02b83792sssb15239ccdf586fc5b176846ffe4878b1aea6a36c8f"
  //user: "User/auth0%7C61790e11a3966d006906596a"}]

getDefaultOrganization(params)

Get a organization from parameters.

Parameters
paramsobjectThe parameters
Returns
string|undefined- organization

getOrganization(organization)

-- TerminusDB API --- Get an organization from the TerminusDB API.

Parameters
organizationstringThe organization
Returns
object- organization

getOrgInvite(inviteId, orgName)

-- TerminusX API --- Get the invitation info

Parameters
inviteIdstringThe invite id to retrieve.
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
const fullInviteId="Organization/my_team_name/invitations/Invitation/7ad0c9eb82b6175bcda9c0dfc
2ac51161ef5ba7cb0988d992c4bce82b3fa5d25"
accessControl.getOrgInvite(fullInviteId).then(result=>{
 console.log(result)
})

getOrgUsers(orgName)

-- TerminusX and TerminusDB API -- Get all the organization's users and roles,

Parameters
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.getOrgUsers().then(result=>{
 console.log(result)
})

//this function will return an array of capabilities with users and roles
//-- TerminusX --  response array example
//[{capability: "Capability/3ea26e1d698821c570afe9cb4fe81a3......"
//     email: {@type: "xsd:string", @value: "user@terminusdb.com"}
//     picture: {@type: "xsd:string",…}
//     role: "Role/dataReader"
//     scope: "Organization/my_org_name"
//     user: "User/auth0%7C613f5dnndjdjkTTT"}]
//
//
// -- Local Installation -- response array example
//[{ "@id":"User/auth0%7C615462f8ab33f4006a6bee0c",
//  "capability": [{
//   "@id":"Capability/c52af34b71f6f8916ac0115ecb5fe0e31248ead8b1e3d100852015...",
//   "@type":"Capability",
//  "role": [{
//    "@id":"Role/admin",
//    "@type":"Role",
//    "action": ["instance_read_access"],
//     "name":"Admin Role"
//     }],
//  "scope":"Organization/@team"}]]

getPendingOrgInvites(orgName)

-- TerminusX API --- Get the pending invitations list.

Parameters
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
const invitationList = accessControl.getPendingOrgInvites().then(result=>{
   console.log(invitationList)

})
//this will return an array of invitations object like this
//[{@id: "Organization/my_team_name/invitations/Invitation/7ad0c9eb82b6175bcda9c0dfc2ac51161ef5ba
cb0988d992c4bce82b3fa5d25"
//      @type: "Invitation"
//      creation_date: "2021-10-22T11:13:28.762Z"
//      email_to: "new_user@terminusdb.com"
//      invited_by: "User/auth0%7C6162f8ab33567406a6bee0c"
//      role: "Role/dataReader"
//      status: "needs_invite"}]

getTeamUserRole(orgName)

-- TerminusX API --- Get the user role for a given organization or the default organization The user is identified by the jwt or the access token

Parameters
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.getTeamUserRole().then(result=>{
 console.log(result)
})

//response object example
{"userRole":"Role/admin"}

getTeamUserRoles(userName, orgName)

-- TerminusX and TerminusDB API -- Get the user roles for a given organization or the default organization,

Parameters
userNamestringThe organization name.
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.getTeamUserRole("myUser").then(result=>{
 console.log(result)
})

//response object example
{
 "@id": "User/myUser",
  "capability": [
        {
          "@id":"Capability/server_access",
          "@type":"Capability",
          "role": [{
             "@id":"Role/reader",
              "@type":"Role",
             "action": [
                "instance_read_access",
             ],
              "name":"reader"
            }],
          "scope":"Organization/myteam"
        }
      ],
  "name": "myUser"
}

getUserInfo(orgName)

-- TerminusX API -- Get the userinfo teams ownership and subscription

Parameters
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.getUserInfo().then(result=>{
   console.log(result)
})

ifOrganizationExists(orgName)

-- TerminusX API --- Check if the organization exists. it is a Head call . IMPORTANT This does not work with the API-TOKEN.

Parameters
orgNamestringThe organization name to check if exists.
Returns
PromiseA promise that returns the call status object, 200: if the organization exists and 404: if the organization does not exist

manageCapability(userName, resourceName, rolesArr, operation, scopeType)

-- TerminusdDB API --- Grant/Revoke Capability

Parameters
userNamestringthe document user id
resourceNamestringthe name of a (database or team)
rolesArrarraythe roles name list
operationtypedef.CapabilityCommandgrant/revoke operation
scopeTypetypedef.ScopeTypethe resource type (database or organization)
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
//we add an user to an organization and manage users' access
//the user myUser can  access the Organization and all the database under the organization with "reader" Role
client.manageCapability(myUser,myteam,[reader],"grant","organization").then(result=>{
 consol.log(result)
})

//the user myUser can  access the database db__001 under the organization myteam
//with "writer" Role
client.manageCapability(myUser,myteam/db__001,[writer],"grant","database").then(result=>{
 consol.log(result)
})

removeUserFromOrg(userId, orgName)

-- TerminusX API -- Remove an user from an organization, only an admin user can remove an user from an organization

Parameters
userIdstringThe id of the user to be removed. (this is the document user's @id)
orgNamestringThe organization name in which the user is to be removed.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.removeUserFromOrg("User/auth0%7C613f5dnndjdjkTTT","my_org_name").then(result=>{
 console.log(result)
})

sendAccessRequest(email, affiliation, note, orgName)

-- TerminusX API -- Get all the access request list for a specify organization

Parameters
emailstringthe user email.
affiliationstringthe user affiliation, company, university etc..
notestringthe message for the team admin
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.sendAccessRequest("myemail@terminusdb.com",
 "my_company",
 "please add me to your team"
).then(result=>{
 console.log(result)
})

sendOrgInvite(userEmail, role, note, orgName)

-- TerminusX API --- Send a new invitation

Parameters
userEmailstringThe email of user.
rolestringThe role for user. (the document @id role like Role/collaborator)
notestringThe note to send with the invitation.
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
accessControl.sendOrgInvite("new_user@terminusdb.com","Role/admin",
"please join myteam").then(result=>{
   console.log(result)
})

setApiKey(atokenpi)

Sets the API token for the object, to request a token create an account in https://terminusdb.com/

Parameters
atokenpistringThe API token to use to connect with TerminusX

setApiToken(atokenpi)

Sets the API token for the object, to request a token create an account in https://terminusdb.com/

Parameters
atokenpistringThe API token to use to connect with TerminusX

setJwtToken(jwt)

Sets the Jwt token for the object

Parameters
jwtstringThe jwt api token to use

updateOrgInviteStatus(inviteId, accepted, orgName)

-- TerminusX API --- Accept /Reject invitation. if the invitation has been accepted we add the current user to the organization. the only user that can accept this invitation is the user registered with the invitation email, we indentify the user with the jwt token

Parameters
inviteIdstringThe invite id to updated.
acceptedbooleanThe status of the invitation.
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
const fullInviteId="Organization/my_team_name/invitations/Invitation/7ad0c9eb82b6175bcda9
c0dfc2ac51161ef5ba7cb0988d992c4bce82b3fa5d25"
accessControl.updateOrgInviteStatus(fullInviteId,true).then(result=>{
  console.log(result)
})

updateUserRole(userId, capabilityId, scope, role, orgName)

-- TerminusX API -- Update user's a role for a resource (organization/database), (this api works only in terminusX)

Parameters
userIdstringThe user's id.
capabilityIdstringThe capability id.
scopestringThe resource name/id.
rolestringThe user role to be updated.
orgNamestringThe organization name.
Returns
PromiseA promise that returns the call response object, or an Error if rejected.
Example: JavaScript
const dbId = "UserDatabase/acfcc2db02b83792sssb15239ccdf586fc5b176846ffe4878b1aea6a36c8f"
const capId= "Capability/b395e8523d509dec6b33aefc9baed3b2e2bfadbd4c79d4ff9b20dce2b14e2edc"
accessControl.updateUserRole('User/auth0%7C61790e11a3966d006906596a',capId,dbId,
"Role/dataUpdater").then(result=>{
     console.log(result)

})

View

We bundle the useful functions in a View object and just export that for ease of consumption

matchCell()

Called to test whether a specific cell is matched by a set of rules returns array of rules that matched

matchColumn()

Called to test whether an entire column of results is matched by a set of rules returns array of rules that matched

matchEdge()

Called to test whether a specific edge (source -> target) is matched by a set of rules returns array of rules that matched

matchFrame()

Called to test whether a specific frame is matched by a set of rules

matchNode()

Called to test whether a specific node is matched by a set of rules returns array of rules that matched

matchRow()

Called to match an entire row of results is matched by a set of rules returns array of rules that matched

rule()

Shorthand functions for accessing the pattern matching capabilities

WOQLQuery

defines the internal functions of the woql query object - the

add_quad(subject, predicate, object, graphRef)

Adds quads according to the pattern [S,P,O,G]

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphReftypedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery

add_triple(subject, predicate, object)

Adds triples according to the the pattern [subject,predicate,object]

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery

added_quad(subject, predicate, object, graphRef-)

Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph) removed from the current commit

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphRef-typedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery

added_triple(subject, predicate, object)

Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object) added in the current layer

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery

addSubQuery()

Internal library function which adds a subquery and sets the cursor

addSubQuery(Subq)

Parameters
SubqWOQLQuery
Returns
WOQLQuery

all(Subj, Pred, Obj, Graph)

Parameters
Subjstring|VarThe IRI of a triple’s subject or a variable
Predstring|VarThe IRI of a property or a variable
Objstring|VarThe IRI of a node or a variable, or a literal
Graphtypedef.GraphRefthe resource identifier of a graph possible
Returns
WOQLQuery- A WOQLQuery which contains the pattern matching expression

all(Subj, Pred, Obj, Graph)

Parameters
Subjstring|VarThe IRI of a triple’s subject or a variable
Predstring|VarThe IRI of a property or a variable
Objstring|VarThe IRI of a node or a variable, or a literal
Graphtypedef.GraphRefthe resource identifier of a graph possible
Returns
WOQLQuery- A WOQLQuery which contains the pattern matching expression

and(subqueries)

Logical conjunction of the contained queries - all queries must match or the entire clause fails

Parameters
subqueriesWOQLQueryA list of one or more woql queries to execute as a conjunction
Returns
WOQLQuery- A WOQLQuery object containing the conjunction of queries

arop()

Wraps arithmetic operators in the appropriate json-ld

as(varList)

Parameters
varListarray|string|Varvariable number of arguments

asv()

Wraps the elements of an AS variable in the appropriate json-ld

boolean(tf)

Parameters
tfboolean
Returns
object

boolean(tf)

Parameters
tfboolean
Returns
object

cleanGraph()

Transforms a graph filter or graph id into the proper json-ld form

cleanObject()

Transforms whatever is passed in as the object of a triple into the appropriate json-ld form (variable, literal or id)

cleanPredicate()

Transforms whatever is passed in as the predicate (id or variable) into the appropriate json-ld form

cleanSubject()

Transforms whatever is passed in as the subject into the appropriate json-ld for variable or id

comment(comment, subquery)

Adds a text comment to a query - can also be used to wrap any part of a query to turn it off

Parameters
commentstringtext comment
subqueryWOQLQueryquery that is "commented out"
Returns
WOQLQuery

compilePathPattern()

Turns a textual path pattern into a JSON-LD description

concat(varList, resultVarName)

takes a variable number of string arguments and concatenates them into a single string

Parameters
varListarray|string|Vara variable representing a list or a list of variables or strings - variables can be embedded in the string if they do not contain spaces
resultVarNamestring|VarA variable or string containing the output string
Returns
WOQLQueryA WOQLQuery which contains the Concatenation pattern matching expression

containsUpdate()

Does this query contain an update

context()

sets the value of the current json-ld context on a full query scope

count(countVarName, subquery)

Creates a count of the results of the query

Parameters
countVarNamestring|number|Varvariable or integer count
subqueryWOQLQuery
Returns
WOQLQueryA WOQLQuery object containing the count sub Query

dataList()

takes input that can be either a string (variable name) or an array - each element of the array is a member of the list

dataValueList()

Wraps data values

delete_document(IRI)

Delete a document from the graph.

Parameters
IRIstringThe document id or a variable
Returns
WOQLQueryWOQLQuery

delete_quad(subject, predicate, object, graphRef)

Deletes a single triple from the graph [Subject, Predicate, Object, Graph]

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphReftypedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery- A WOQLQuery which contains the Delete Quad Statement

delete_triple(subject, predicate, object)

Deletes a single triple from the default graph of the database

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery- A WOQLQuery which contains the Triple Deletion statement

distinct(varNames)

Filter the query to return only results that are distinct in the given variables

Parameters
varNamesstring|Varthese variables are guaranteed to be unique as a tuple
Returns
WOQLQuery

div(args)

Division - integer division - args are divided left to right

Parameters
argsstring|number|Varnumbers for division
Returns
WOQLQueryA WOQLQuery which contains the division expression

divide(args)

Divides numbers N1...Nn by each other left, to right precedence

Parameters
argsstring|number|Varnumbers to tbe divided
Returns
WOQLQueryA WOQLQuery which contains the division expression

dot(document, field, value)

Extract the value of a key in a bound document.

Parameters
documentstring|VarDocument which is being accessed.
fieldstring|VarThe field from which the document which is being accessed.
valuestring|VarThe value for the document and field.
Returns
WOQLQueryA WOQLQuery which contains the a dot Statement

eq(varName, varValue)

Matches if a is equal to b

Parameters
varNamestring|Varliteral, variable or id
varValuestring|Varliteral, variable or id
Returns
WOQLQuery

eval(arithExp, resultVarName)

Evaluates the passed arithmetic expression and generates or matches the result value

Parameters
arithExpobject|WOQLQuery|stringquery or JSON-LD representing the query
resultVarNamestring|Varoutput variable
Returns
WOQLQuery

evaluate(arithExp, resultVarName)

Evaluates the passed arithmetic expression and generates or matches the result value. Alias for eval() to support both naming conventions in fluent/chained style.

Parameters
arithExpobject|WOQLQuery|stringA WOQL query containing a valid arithmetic expression
resultVarNamestring|number|VarEither a variable to store the result, or a numeric literal to test against the evaluated expression
Returns
WOQLQuery

execute()

Use instead woqlclient.query('myWOQLQuery')

exp(varNum, expNum)

Exponent - raises varNum01 to the power of varNum02

Parameters
varNumstring|number|Vara variable or numeric containing the number to be raised to the power of the second number
expNumnumbera variable or numeric containing the exponent
Returns
WOQLQueryA WOQLQuery which contains the exponent expression

expandVariable(varname)

Transforms strings that start with v: into variable json-ld structures

Parameters
varnameunknownwill be transformed if it starts with v:

findLastProperty(json)

Finds the last woql element that has a subject in that is a property id used for triplebuilder to chain further calls - when they may be inside ands or ors or subqueries

Parameters
jsonobject

findLastSubject(json)

Finds the last woql element that has a subject in it and returns the json for that used for triplebuilder to chain further calls - when they may be inside ands or ors or subqueries

Parameters
jsonobject

floor(varNum)

Generates the nearest lower integer to the passed number

Parameters
varNumstring|number|VarVariable or numeric containing the number to be floored
Returns
WOQLQueryA WOQLQuery which contains the floor expression

from(graphRef-, query)

Specifies the database URL that will be the default database for the enclosed query

Parameters
graphRef-typedef.GraphRefA valid graph resource identifier string
queryWOQLQueryThe query
Returns
WOQLQueryA WOQLQuery object containing the from expression

get(asvars, queryResource)

Use the document inteface to import documents

Parameters
asvarsVars|array.<Var>an array of AsVar variable mappings (see as for format below)
queryResourceWOQLQueryan external resource (remote, file, post) to query
Returns
WOQLQueryA WOQLQuery which contains the get expression

getContext()

Retrieves the value of the current json-ld context

getLimit()

Functions to manipulate and check the paging related properties of a query

getPagingProperty()

Returns the value of one of the 'paging' related properties (limit, start,...)

graph(graphRef)

Sets the graph resource ID that will be used for subsequent chained function calls

Parameters
graphReftypedef.GraphRefResource String identifying the graph which will be used for subsequent chained schema calls
Returns
WOQLQueryA WOQLQuery which contains the partial Graph pattern matching expression

graph(graphRef)

Sets the graph resource ID that will be used for subsequent chained function calls

Parameters
graphReftypedef.GraphRefResource String identifying the graph which will be used for subsequent chained schema calls
Returns
WOQLQueryA WOQLQuery which contains the partial Graph pattern matching expression

greater(varNum01, varNum02)

Compares the value of v1 against v2 and returns true if v1 is greater than v2

Parameters
varNum01string|number|Vara variable or numeric containing the number to be compared
varNum02string|number|Vara variable or numeric containing the second comporator
Returns
WOQLQueryA WOQLQuery which contains the comparison expression

group_by(gvarlist, groupedvar, output, groupquery)

Groups the results of the contained subquery on the basis of identical values for Groupvars, extracts the patterns defined in PatternVars and stores the results in GroupedVar

Parameters
gvarlistarray|string|VarEither a single variable or an array of variables
groupedvararray|string|VarEither a single variable or an array of variables
outputstring|Varoutput variable name
groupqueryWOQLQueryThe query whose results will be grouped
Returns
WOQLQueryA WOQLQuery which contains the grouping expression

idgen(prefix, inputVarList, outputVar)

Generates the node's ID combined the variable list with a specific prefix (URL base). If the input variables's values are the same, the output value will be the same.

Parameters
prefixstring
inputVarListstring|arraythe variable input list for generate the id
outputVarstringthe output variable name

idgen_random(prefix, outputVar)

Generates a random ID with a specified prefix Uses cryptographically secure random base64 encoding to generate unique identifiers

Parameters
prefixstringprefix for the generated ID
outputVarstringvariable that stores the generated ID
Returns
WOQLQueryA WOQLQuery which contains the random ID generation pattern idgen_random("Person/", "v:person_id")

immediately(subquery)

Runs the query without backtracking on side-effects

Parameters
subquerystring|WOQLQueryWOQL Query objects
Returns
WOQLQueryA WOQLQuery object containing the immediately sub Query

insert(id, type, refGraph)

Parameters
idstring|VarIRI string or variable containing
typestring|VarIRI string or variable containing the IRI of the
refGraphtypedef.GraphRefOptional Graph resource identifier
Returns
WOQLQueryA WOQLQuery which contains the insert expression

insert(id, type, refGraph)

Parameters
idstring|VarIRI string or variable containing
typestring|VarIRI string or variable containing the IRI of the
refGraphtypedef.GraphRefOptional Graph resource identifier
Returns
WOQLQueryA WOQLQuery which contains the insert expression

insert_document(docjson, IRI)

Insert a document in the graph.

Parameters
docjsonobjectThe document to insert. Must either have an '@id' or have a class specified key.
IRIstringAn optional identifier specifying the document location.
Returns
WOQLQueryWOQLQuery

into(graphRef-, subquery)

Specifies the graph resource to write the contained query into

Parameters
graphRef-typedef.GraphRefA valid graph resource identifier string
subqueryWOQLQueryThe query which will be written into the graph
Returns
WOQLQueryA WOQLQuery which will be written into the graph in question

iri(s)

Parameters
sstring
Returns
object

iri(s)

Parameters
sstring
Returns
object

isa(instanceIRI, classId)

Tests whether a given instance IRI has type Class, according to the current state of the DB

Parameters
instanceIRIstring|VarA string IRI or a variable that identify the class instance
classIdstring|VarA Class IRI or a variable
Returns
WOQLQueryA WOQLQuery object containing the type test

jlt()

Wraps the passed value in a json-ld literal carriage

jobj()

Transforms a javascript representation of a query into a json object if needs be

join(varList, glue, resultVarName)

Joins a list variable together (Input) into a string variable (Output) by glueing the strings together with Glue

Parameters
varListstring|array|Vara variable representing a list or a list of strings and / or variables
gluestring|VarA variable (v:glue) or (glue) string representing the characters to put in between the joined strings in input
resultVarNamestring|VarA variable or string containing the output string
Returns
WOQLQueryA WOQLQuery which contains the Join pattern matching expression

json(json)

converts back and forward from json if the argument is present, the current query is set to it, if the argument is not present, the current json version of this query is returned

Parameters
jsonobjecta query in json format
Returns
object

length(inputVarList, resultVarName)

Calculates the length of the list in va and stores it in vb

Parameters
inputVarListstring|arrayEither a variable representing a list or a list of variables or literals
resultVarNamestring|VarA variable in which the length of the list is stored or the length of the list as a non-negative integer
Returns
WOQLQueryA WOQLQuery which contains the Length pattern matching expression

less(varNum01, varNum02)

Compares the value of v1 against v2 and returns true if v1 is less than v2

Parameters
varNum01string|number|Vara variable or numeric containing the number to be compared
varNum02string|number|Vara variable or numeric containing the second comporator
Returns
WOQLQueryA WOQLQuery which contains the comparison expression

like(stringA, stringB, distance)

Generates a string Leverstein distance measure between stringA and stringB

Parameters
stringAstring|Varstring literal or variable representing a string to be compared
stringBstring|Varstring literal or variable representing the other string to be compared
distancenumber|string|Varvariable representing the distance between the variables
Returns
WOQLQueryA WOQLQuery which contains the Like pattern matching expression

limit(limit, subquery)

Specifies a maximum number of results that will be returned from the subquery

Parameters
limitnumber|stringA variable that refers to an non-negative integer or a non-negative integer
subqueryWOQLQueryA subquery whose results will be limited
Returns
WOQLQueryA WOQLQuery whose results will be returned starting from the specified offset

literal(s, t)

Parameters
sanythe value of the literal
tstringthe type of the literal, e.g. 'xsd:string', 'xsd:boolean'
Returns
object- a WOQL DataValue object with the given type and value

literal(s, t)

Parameters
sany
tstring
Returns
object

loadDefaultVocabulary()

vocabulary elements that can be used without prefixes in woql.js queries

lower(inputVarName, resultVarName)

Changes a string to lower-case

Parameters
inputVarNamestring|Varstring or variable representing the non-lowercased string
resultVarNamestring|Varvariable that stores the lowercased string output
Returns
WOQLQueryA WOQLQuery which contains the Lower case pattern matching expression

member(element, list)

Matches if List includes Element

Parameters
elementstring|object|VarEither a variable, IRI or any simple datatype
liststring|array|VarList ([string, literal] or string*) Either a variable representing a list or a list of variables or literals
Returns
WOQLQueryA WOQLQuery which contains the List inclusion pattern matching expression

minus(args)

Subtracts Numbers N1..Nn

Parameters
argsstring|number|Varvariable or numeric containing the value that will be subtracted from
Returns
WOQLQueryA WOQLQuery which contains the subtraction expression

node(node, type)

Parameters
nodestring|VarThe IRI of a node or a variable containing an IRI which will be the subject of the builder functions
typetypedef.FuntionTypeOptional type of builder function to build (default is triple)
Returns
WOQLQuery- A WOQLQuery which contains the partial Node pattern matching expression

node(nodeid, chainType)

Specifies the identity of a node that can then be used in subsequent builder functions. Note that node() requires subsequent chained functions to complete the triples / quads that it produces - by itself it only generates the subject.

Parameters
nodeidstring|VarThe IRI of a node or a variable containing an IRI which will be the subject of the builder functions
chainTypetypedef.FuntionTypeOptional type of builder function to build (default is triple)
Returns
WOQLQuery- A WOQLQuery which contains the partial Node pattern matching expression

not(subquery)

Logical negation of the contained subquery - if the subquery matches, the query will fail to match

Parameters
subquerystring|WOQLQueryA subquery which will be negated
Returns
WOQLQueryA WOQLQuery object containing the negated sub Query

nuke(graphRef)

Deletes all triples in the passed graph (defaults to instance/main)

Parameters
graphReftypedef.GraphRefResource String identifying the graph from which all triples will be removed
Returns
WOQLQuery- A WOQLQuery which contains the deletion expression

nuke(graphRef)

Deletes all triples in the passed graph (defaults to instance/main)

Parameters
graphReftypedef.GraphRefResource String identifying the graph from which all triples will be removed
Returns
WOQLQuery- A WOQLQuery which contains the deletion expression
Example: JavaScript
nuke("schema/main")
//will delete everything from the schema/main graph

once(subquery)

Results in one solution of the subqueries

Parameters
subquerystring|WOQLQueryWOQL Query objects
Returns
WOQLQueryA WOQLQuery object containing the once sub Query

opt(subquery)

Specifies that the Subquery is optional - if it does not match the query will not fail

Parameters
subqueryWOQLQueryA subquery which will be optionally matched
Returns
WOQLQueryA WOQLQuery object containing the optional sub Query

or(subqueries)

Creates a logical OR of the arguments

Parameters
subqueriesWOQLQueryA list of one or more woql queries to execute as alternatives
Returns
WOQLQuery- A WOQLQuery object containing the logical Or of the subqueries

order_by(orderedVarlist)

Orders the results of the contained subquery by a precedence list of variables

Parameters
orderedVarliststring|Var|arrayA sequence of variables, by which to order the results, each optionally followed by either “asc” or “desc” to represent order as a list, by default it will sort the variable in ascending order
Returns
WOQLQueryA WOQLQuery which contains the ordering expression

pad(inputVarName, pad, len, resultVarName)

Pads out the string input to be exactly len long by appending the pad character pad to form output

Parameters
inputVarNamestring|VarThe input string or variable in unpadded state
padstring|VarThe characters to use to pad the string or a variable representing them
lennumber|string|VarThe variable or integer value representing the length of the output string
resultVarNamestring|Varstores output
Returns
WOQLQueryA WOQLQuery which contains the Pad pattern matching expression

parameterError()

Basic Error handling

parameterError(msg)

Parameters
msgstring
Returns
WOQLQuery

path(subject, pattern, object, resultVarName)

Performs a path regular expression match on the graph

Parameters
subjectstring|VarAn IRI or variable that refers to an IRI representing the subject, i.e. the starting point of the path
patternstring(string) - A path regular expression describing a pattern through multiple edges of the graph (see: https://terminusdb.com/docs/path-query-reference-guide)
objectstring|VarAn IRI or variable that refers to an IRI representing the object, i.e. ending point of the path
resultVarNamestring|VarA variable in which the actual paths traversed will be stored
Returns
WOQLQuery- A WOQLQuery which contains the path regular expression matching expression

plus(args)

Adds the numbers together

Parameters
argsstring|number|Vara variable or numeric containing the values to add
Returns
WOQLQueryA WOQLQuery which contains the addition expression

post(url, formatObj, source)

Identifies a resource as a local path on the client, to be sent to the server through a HTTP POST request, with the format defined through the options

Parameters
urlstringThe Path on the server at which the file resource can be accessed
formatObjtypedef.DataFormatObjimput options, optional
sourcestringIt defines the source of the file, it can be 'url','post'
Returns
WOQLQueryA WOQLQuery which contains the Post resource identifier

prettyPrint(clang)

Returns a script version of the query

Parameters
clangstringeither "js" or "python"

put(varsToExp, query, fileResource)

Use the document inteface to import documents

Parameters
varsToExpVars|array.<Var>an array of AsVar variable mappings (see as for format below)
queryWOQLQueryThe query which will be executed to produce the results
fileResourcestringan file resource local to the server
Returns
WOQLQueryA WOQLQuery which contains the put expression

quad(subject, predicate, object, graphRef)

Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph)

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphReftypedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery

re(pattern, inputVarName, resultVarList)

Matches the regular expression defined in Patern against the Test string, to produce the matched patterns in Matches

Parameters
patternstringstring or variable using normal PCRE regular expression syntax with the exception that special characters have to be escaped twice (to enable transport in JSONLD)
inputVarNamestring|Varstring or variable containing the string to be tested for patterns with the regex
resultVarListstring|array|object|Varvariable representing the list of matches or a list of strings or variables
Returns
WOQLQueryA WOQLQuery which contains the Regular Expression pattern matching expression

read_document(IRI, output)

Read a node identified by an IRI as a JSON-LD document

Parameters
IRIstringThe document id or a variable to read
outputstringVariable which will be bound to the document.
Returns
WOQLQueryWOQLQuery

remote(remoteObj, formatObj)

Identifies a remote resource by URL and specifies the format of the resource through the options

Parameters
remoteObjobjectThe URL at which the remote resource can be accessed
formatObjtypedef.DataFormatObjThe format of the resource data {}
Returns
WOQLQueryA WOQLQuery which contains the remote resource identifier

removed_quad(subject, predicate, object, graphRef-)

Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph) removed from the current commit

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
graphRef-typedef.GraphRefA valid graph resource identifier string
Returns
WOQLQuery

removed_triple(subject, predicate, object)

Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object) added in the current commit

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery

select(varNames)

Filters the query so that only the variables included in [V1...Vn] are returned in the bindings

Parameters
varNamesstring|Varonly these variables are returned
Returns
WOQLQuery

setPagingProperty()

Sets the value of one of the paging_transitive_properties properties

setVocabulary()

Provides the query with a 'vocabulary' a list of well known predicates that can be used without prefixes mapping: id: prefix:id ...

size(resourceId, resultVarName)

Calculates the size in bytes of the contents of the resource identified in ResourceID

Parameters
resourceIdstring|VarA valid resource identifier string (can refer to any graph / branch / commit / db)
resultVarNamestring|VarThe variable name

slice(inputList, resultVarName, start, end)

Extracts a contiguous subsequence from a list, following JavaScript's slice() semantics

Parameters
inputListstring|array|VarEither a variable representing a list or a list of variables or literals
resultVarNamestring|VarA variable in which the sliced list is stored
startnumber|string|VarThe start index (0-based, supports negative indices)
endnumber|string|VarThe end index (exclusive, optional - defaults to list length)
Returns
WOQLQueryA WOQLQuery which contains the Slice pattern matching expression let [result] = vars("result") slice(["a", "b", "c", "d"], result, 1, 3) // result = ["b", "c"] slice(["a", "b", "c", "d"], result, -2) // result = ["c", "d"]

split(inputVarName, separator, resultVarName)

Splits a string (Input) into a list strings (Output) by removing separator

Parameters
inputVarNamestring|VarA string or variable representing the unsplit string
separatorstring|VarA string or variable containing a sequence of charatcters to use as a separator
resultVarNamestring|Varvariable that stores output list
Returns
WOQLQueryA WOQLQuery which contains the Split pattern matching expression

star()

Simple composite functions which produce WOQL queries

star(graph, subject, predicate, object)

Generates a query that by default matches all triples in a graph identified by "graph" or in all the current terminusDB's graph

Parameters
graphstring|booleanfalse or the resource identifier of a graph possible value are schema/{main - myschema - *} | instance/{main - myschema - *} | inference/{main - myschema - *}
subjectstring|VarThe IRI of a triple’s subject or a variable, default value "v:Subject"
predicatestring|VarThe IRI of a property or a variable, default value "v:Predicate"
objectstring|VarThe IRI of a node or a variable, or a literal, default value "v:Object"
Returns
WOQLQueryA WOQLQuery which contains the pattern matching expression

start(start, subquery)

Specifies an offset position in the results to start listing results from

Parameters
startnumber|string|VarA variable that refers to an interger or an integer literal
subqueryWOQLQueryWOQL Query object, you can pass a subquery as an argument or a chained query
Returns
WOQLQueryA WOQLQuery whose results will be returned starting from the specified offset

string(s)

Parameters
sstring
Returns
object

string(s)

Parameters
sstring
Returns
object

sub(classA, classB)

Returns true if ClassA subsumes ClassB, according to the current DB schema

Parameters
classAstringClassA
classBstringClassB
Returns
booleanWOQLQuery

substr(string, before, length, after, subString)

Substring

Parameters
stringstring|VarString or variable
beforenumber|Varinteger or variable (characters from start to begin)
lengthnumber|Varinteger or variable (length of substring)
afternumber|Varinteger or variable (number of characters after substring)
subStringstring|VarString or variable
Returns
WOQLQuery

sum(subquery, total)

computes the sum of the List of values passed. In contrast to other arithmetic functions, sum self-evaluates - it does not have to be passed to evaluate()

Parameters
subqueryWOQLQuerya subquery or ([string or numeric]) - a list variable, or a list of variables or numeric literals
totalstring|Varthe variable name with the sum result of the values in List
Returns
WOQLQuery- A WOQLQuery which contains the Sum expression

times(args)

Multiplies numbers N1...Nn together

Parameters
argsstring|number|Vara variable or numeric containing the value
Returns
WOQLQueryA WOQLQuery which contains the multiplication expression

trim(inputStr, resultVarName)

Remove whitespace from both sides of a string:

Parameters
inputStrstring|VarA string or variable containing the untrimmed version of the string
resultVarNamestring|VarA string or variable containing the trimmed version of the string
Returns
WOQLQueryA WOQLQuery which contains the Trim pattern matching expression

triple(subject, predicate, object)

Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object)

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objectstring|VarThe IRI of a node or a variable, or a literal
Returns
WOQLQuery

triple_count(resourceId, tripleCount)

Calculates the number of triples of the contents of the resource identified in ResourceID

Parameters
resourceIdstring|VarA valid resource identifier string (can refer to any graph / branch / commit / db)
tripleCountstring|number|VarAn integer literal with the size in bytes or a variable containing that integer
Returns
WOQLQueryA WOQLQuery which contains the size expression

true()

A function that always matches, always returns true

Returns
WOQLQueryA WOQLQuery object containing the true value that will match any pattern

type_of(elementId, elementType)

Returns true if 'elementId' is of type 'elementType', according to the current DB schema

Parameters
elementIdstring|Varthe id of a schema graph element
elementTypestring|Varthe element type
Returns
WOQLQueryA WOQLQuery object containing the type_of pattern matching rule

typecast(varName, varType, resultVarName)

Casts the value of Input to a new value of type Type and stores the result in CastVar

Parameters
varNamestring|number|object|VarEither a single variable or a literal of any basic type
varTypestring|VarEither a variable or a basic datatype (xsd / xdd)
resultVarNamestring|Varsave the return variable
Returns
WOQLQueryA WOQLQuery which contains the casting expression

unique(prefix, inputVarList, resultVarName)

Generate a new IRI from the prefix and a hash of the variables which will be unique for any given combination of variables

Parameters
prefixstringA prefix for the IRI - typically formed of the doc prefix and the classtype of the entity (“doc:Person”)
inputVarListarray|string|VarAn array of variables and / or strings from which the unique hash will be generated
resultVarNamestring|VarVariable in which the unique ID is stored
Returns
WOQLQueryA WOQLQuery object containing the unique ID generating function

update_document(docjson, IRI)

Update a document identified by an IRI

Parameters
docjsonobjectThe document to update. Must either have an '@id' or have a class specified key.
IRIstringAn optional identifier specifying the document location.
Returns
WOQLQueryWOQLQuery

update_quad(subject, predicate, newObject, graph)

Update a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph)

Parameters
subjectstringThe IRI of a triple’s subject or a variable
predicatestringThe IRI of a property or a variable
newObjectstringThe value to update or a literal
graphstringthe resource identifier of a graph possible value are schema/{main - myschema - *} | instance/{main - myschema - *} | inference/{main - myschema - *}
Returns
WOQLQueryA WOQLQuery which contains the a Update Quad Statement

update_quad(subject, predicate, newObject, graphRef)

Update a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph)

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
newObjectstring|VarThe value to update or a literal
graphReftypedef.GraphRefA valid graph resource identifier string
Returns
WOQLQueryA WOQLQuery which contains the a Update Quad Statement

update_triple(subject, predicate, newObjValue, oldObjValue)

Update a pattern matching rule for the triple (Subject, Predicate, oldObjValue) with the new one (Subject, Predicate, newObjValue)

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
newObjValuestring|VarThe value to update or a literal
oldObjValuestring|VarThe old value of the object
Returns
WOQLQueryA WOQLQuery which contains the a Update Triple Statement

update_triple(subject, predicate, newObjValue, oldObjValue)

Update a pattern matching rule for the triple (Subject, Predicate, oldObjValue) with the new one (Subject, Predicate, newObjValue)

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
newObjValuestring|VarThe value to update or a literal
oldObjValuestring|VarThe old value of the object
Returns
WOQLQueryA WOQLQuery which contains the a Update Triple Statement

updated()

Called to inidicate that this query will cause an update to the DB

updated()

Returns
WOQLQuery

upper(inputVarName, resultVarName)

Changes a string to upper-case

Parameters
inputVarNamestring|Varstring or variable representing the uncapitalized string
resultVarNamestring|Varvariable that stores the capitalized string output
Returns
WOQLQueryA WOQLQuery which contains the Upper case pattern matching expression

using(refPath, subquery)

Query running against any specific commit Id

Parameters
refPathstringpath to specific reference Id or commit Id
subqueryWOQLQuerysubquery for the specific commit point
Returns
WOQLQuery

value(subject, predicate, objValue)

Creates a pattern matching rule for triple [Subject, Predicate, Object] add extra information about the type of the value object

Parameters
subjectstring|VarThe IRI of a triple’s subject or a variable
predicatestring|VarThe IRI of a property or a variable
objValuestring|number|boolean|Varan specific value
Returns
WOQLQueryA WOQLQuery which contains the a quad or a triple Statement

valueList()

takes a list of input that can be any value

vlist()

creates an unadorned variable name list

wform(opts)

JSON LD Format Descriptor

Parameters
optsobject

wrapCursorWithAnd()

Contains definitions of the WOQL functions which map directly to JSON-LD types All other calls and queries can be composed from these