Skip to main content
Last updated

Database

create-table

Use create-table to create a table identified by the specified table name.

Basic syntax

To create a table identified by the specified table name, use the following syntax:

pact
(create-table table)
pact
(create-table table)

Prerequisites

Before using this function in a Pact module, you must define the table fields using the defschema declaration and the table identifier using the deftable declaration. Creating the table is a separate step that is outside of the Pact module where the schema and identifier are defined.

Arguments

Use the following argument to specify the table name you want to create using the create-table Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table to create.

Return values

The create-table function returns a string representing the identifier of the created table.

Example

The following example demonstrates how to use the create-table function to create a table identified by accounts that can be used for storing account information:

pact
(create-table accounts)
pact
(create-table accounts)

The following example illustrates using the create-table function after defining the table schema and table identifier:

pact
(defschema wallet-schema	name : string)(deftable wallet-table:{wallet-schema}) ... (create-table wallet-table)
pact
(defschema wallet-schema	name : string)(deftable wallet-table:{wallet-schema}) ... (create-table wallet-table)

describe-keyset

Use describe-keyset to retrieve metadata for a specified keyset.

Note: You can only use this function at the top level of your code. The function fails if used within module code.

Basic syntax

To get metadata for the specified keyset name, use the following syntax:

pact
(describe-keyset keyset)
pact
(describe-keyset keyset)

Arguments

Use the following argument to specify the keyset for which to retrieve metadata using the describe-keyset Pact function.

ArgumentTypeDescription
keysetstringSpecifies the name of the keyset that you want to retrieve metadata for.

Return values

The describe-keyset function returns a guard.

The returned object includes the following properties:

  • pred: The predicate function associated with the keyset.
  • keys: An array of public keys associated with the keyset.

Examples

The following example retrieves metadata for a keyset named 'admin-keyset' in the Pact REPL:

lisp
pact> (describe-keyset 'admin-keyset){  "pred": "keys-all",  "keys": [    "ba54b224d1924dd98403f5c751abdd10de6cd81b0121800bf7bdbdcfaec7388d",    "8cc94f8a4b43f4d9e3f8c5dca3966ea000f13ecbd79abc01bc7c00faacd06a5e"  ]}
lisp
pact> (describe-keyset 'admin-keyset){  "pred": "keys-all",  "keys": [    "ba54b224d1924dd98403f5c751abdd10de6cd81b0121800bf7bdbdcfaec7388d",    "8cc94f8a4b43f4d9e3f8c5dca3966ea000f13ecbd79abc01bc7c00faacd06a5e"  ]}

describe-module

Use describe-module to get metadata for a specified module. This function returns an object with fields including name, hash, blessed, code, and keyset.

Note: This function is only allowed in /local in chainweb.

Basic syntax

To get metadata for a module, use the following syntax:

pact
(describe-module module)
pact
(describe-module module)

Arguments

Use the following argument to specify the module for the describe-module Pact function.

ArgumentTypeDescription
modulestringSpecifies the name of the module to describe.

Return values

The describe-module function returns an object with metadata for the specified module.

Examples

The following example demonstrates how to use describe-module function to describe a loaded module:

pact
pact> (module election-gas-station GOVERNANCE (defcap GOVERNANCE () true))"Loaded module election-gas-station, hash S6Dtzd7TzbRkYV6_5G5JRhjtF9Ztvaw7LuUEHEeRivQ" pact> (describe-module "election-gas-station"){  "blessed": []  ,"code": "(module election-gas-station GOVERNANCE (defcap GOVERNANCE () true))"  ,"hash": "S6Dtzd7TzbRkYV6_5G5JRhjtF9Ztvaw7LuUEHEeRivQ"  ,"interfaces": []  ,"keyset": "Governance {_gGovernance = Right (Def {_dDefName = DefName {_unDefName = "GOVERNANCE"}, _dModule = ModuleName {_mnName = "election-gas-station", _mnNamespace = Nothing}, _dDefType = Defcap, _dFunType = FunType {_ftArgs = [], _ftReturn = TyVar {_tyVar = TypeVar {_tvName = "a", _tvConstraint = []}}}, _dDefBody = Scope (TList {_tList = [TLiteral {_tLiteral = LBool {_lBool = True}, _tInfo = true}], _tListType = TyAny, _tInfo = (defcap GOVERNANCE () true)}), _dMeta = Meta {_mDocs = Nothing, _mModel = []}, _dDefMeta = Nothing, _dInfo = (defcap GOVERNANCE () true)})}" ,"name": "election-gas-station"}
pact
pact> (module election-gas-station GOVERNANCE (defcap GOVERNANCE () true))"Loaded module election-gas-station, hash S6Dtzd7TzbRkYV6_5G5JRhjtF9Ztvaw7LuUEHEeRivQ" pact> (describe-module "election-gas-station"){  "blessed": []  ,"code": "(module election-gas-station GOVERNANCE (defcap GOVERNANCE () true))"  ,"hash": "S6Dtzd7TzbRkYV6_5G5JRhjtF9Ztvaw7LuUEHEeRivQ"  ,"interfaces": []  ,"keyset": "Governance {_gGovernance = Right (Def {_dDefName = DefName {_unDefName = "GOVERNANCE"}, _dModule = ModuleName {_mnName = "election-gas-station", _mnNamespace = Nothing}, _dDefType = Defcap, _dFunType = FunType {_ftArgs = [], _ftReturn = TyVar {_tyVar = TypeVar {_tvName = "a", _tvConstraint = []}}}, _dDefBody = Scope (TList {_tList = [TLiteral {_tLiteral = LBool {_lBool = True}, _tInfo = true}], _tListType = TyAny, _tInfo = (defcap GOVERNANCE () true)}), _dMeta = Meta {_mDocs = Nothing, _mModel = []}, _dDefMeta = Nothing, _dInfo = (defcap GOVERNANCE () true)})}" ,"name": "election-gas-station"}

In this example, (describe-module 'm) is used to get metadata for the module named 'm'. The function returns an object providing detailed information about the module.

describe-table

Use describe-table to get metadata for a specified table. This function returns an object with fields including module, name, and type.

Basic syntax

To get metadata for a specified table, use the following syntax:

pact
(describe-table table)
pact
(describe-table table)

Arguments

Use the following argument to specify the table for the describe-table Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table to describe.

Return values

The describe-table function returns an object with metadata for the specified table.

Examples

The following example demonstrates use to use the describe-table function in the Pact REPL by loading a module that has a table definition:

pact
pact> (module ledger GOVERNANCE (defcap GOVERNANCE () true) (defschema token-schema id:string uri:string precision:integer supply:decimal) (deftable tokens:{token-schema}))
pact
pact> (module ledger GOVERNANCE (defcap GOVERNANCE () true) (defschema token-schema id:string uri:string precision:integer supply:decimal) (deftable tokens:{token-schema}))

The Pact REPL loads the module and displays the has with output similar to the following:

text
Loaded module m, hash UAnq05ArrOYCFbeJDjCLpWecBq5bS5I0WA6Mj0O041o
text
Loaded module m, hash UAnq05ArrOYCFbeJDjCLpWecBq5bS5I0WA6Mj0O041o
pact
pact> (describe-table tokens){"module": "ledger","name": "tokens","type": "(defschema token-schema  [id:string, uri:string, precision:integer, supply:decimal])"}
pact
pact> (describe-table tokens){"module": "ledger","name": "tokens","type": "(defschema token-schema  [id:string, uri:string, precision:integer, supply:decimal])"}

fold-db

Use fold-db to select rows from a specified table using a predicate query with both a key and a value, and then accumulate the results of the query using a consumer function. The output is sorted by the ordering of keys.

Basic syntax

To select rows from a table, apply a predicate, and accumulate the results using a consumer function, use the following syntax:

pact
(fold-db table query consumer)
pact
(fold-db table query consumer)

Arguments

Use the following arguments to specify the table, predicate, and consumer function for the fold-db Pact function:

ArgumentTypeDescription
tabletable: <{row}>Specifies the table from which to select rows.
querya:string b:object: <{row}>Specifies the predicate function to apply to each row and return a boolean value.
consumerfunction with key: string and value: object: <{row}>Specifies the consumer function used to accumulate results from each row and return the final result from all accumulated results.

Return values

The fold-db function returns a list of accumulated results based on the predicate query and the consumer function.

Examples

The following example demonstrates how to use the fold-db function:

pact
(let  ((query (lambda (k obj) true)) ;; Select all rows   (func (lambda (x) [(at 'firstName x), (at 'b x)])) ;; Example consumer function  )  (fold-db people query func))
pact
(let  ((query (lambda (k obj) true)) ;; Select all rows   (func (lambda (x) [(at 'firstName x), (at 'b x)])) ;; Example consumer function  )  (fold-db people query func))

In this example:

  • (qry (lambda (k obj) true)) is a predicate that selects all rows.
  • (f (lambda (x) [(at 'firstName x), (at 'b x)])) is a consumer function that selects the "firstName" and "b" fields from each row.

The fold-db function is then used to select rows from the people table using the predicate qry and accumulate the results using the consumer function f. The result is a list of accumulated results based on the selected rows and the specified consumer function. The fold-db function is useful for iterating over rows in a table and performing operations in Pact contracts.

insert

Use insert to write an entry in a specified table for a given key of object data. This operation fails if data already exists for the specified key.

Basic syntax

To insert data into a table for a specified key, use the following syntax:

pact
(insert table key object)
pact
(insert table key object)

Arguments

Use the following arguments to specify the table, key, and object data you want to insert using the insert Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table where the entry will be written.
keystringSpecifies the key for which the data will be inserted.
objectobjectSpecifies the object data to be inserted for the specified key.

Return value

The insert function returns a string indicating the success or an exception on failure of the operation.

Examples

The following example demonstrates how to use the insert function to insert information into the accounts table for the account specified using the id for the account:

pact
(insert accounts id { "balance": 0.0, "note": "Created account." })
pact
(insert accounts id { "balance": 0.0, "note": "Created account." })

The following example illustrates a more complete flow from defining the table schema to inserting values into the table:

pact
(defschema coin-schema    balance:decimal    guard:guard) (deftable coin-table:{coin-schema}) (defun create-account:string (account:string guard:guard)     (insert coin-table account      { "balance" : 0.0      , "guard"   : guard      }))
pact
(defschema coin-schema    balance:decimal    guard:guard) (deftable coin-table:{coin-schema}) (defun create-account:string (account:string guard:guard)     (insert coin-table account      { "balance" : 0.0      , "guard"   : guard      }))

keylog

Use keylog to return updates to a specified table for a given key in transactions at or after a specified transaction identifier (txid), in a list of objects indexed by transaction identifiers.

Basic syntax

To retrieve updates to a table for a specific key in transactions at or after a specified txid value, use the following syntax:

pact
(keylog table key txid)
pact
(keylog table key txid)

Arguments

Use the following arguments to specify the table, key, and transaction identifier for which you want to retrieve updates using the keylog Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table that you want to retrieve updates for.
keystringSpecifies the key for retrieving updates.
txidintegerSpecifies the transaction identifier for retrieving updates. Only updates at or after this transaction identifier are included.

Return value

The keylog function returns a list of objects containing updates to the specified table for the given key, indexed by transaction identifier.

Examples

The following example demonstrates how to use the keylog function to retrieve updates for the accounts table for the key "Alice", starting from transaction identifier 123485945:

pact
(keylog accounts "Alice" 123485945)
pact
(keylog accounts "Alice" 123485945)

keys

Use keys to retrieve all the keys in a specified table.

Basic syntax

To retrieve all of the keys for a specified table, use the following syntax:

pact
(keys table)
pact
(keys table)

Arguments

Use the following argument to specify the table from which to retrieve keys using the keys Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table from which to retrieve keys. In the table schema, a row represents the structure of each row in the table.

Return values

The keys function returns an array of strings, where each string represents a key in the specified table.

Examples

The following example demonstrates defining a table schema for an accounts table that stores information about bank accounts, including the balance and owner of each account:

pact
(defschema account  balance:decimal  owner:string) (deftable accounts:{account})
pact
(defschema account  balance:decimal  owner:string) (deftable accounts:{account})

You can then retrieve all of the the keys from the accounts table using the keys function:

pact
pact> (keys accounts)[]
pact
pact> (keys accounts)[]

list-modules

Use list-modules to get all of the modules deployed on a particular chain.

Note: This function is only allowed in /local in chainweb.

Basic syntax

To list all modules in /local, use

pact
(list-modules)
pact
(list-modules)

Arguments

None

Return values

The list-modules function returns a list of all module names (including their namespace) stored on-chain

Examples

The following example deploys a simple module in the repl, then calls list-modules.

pact>(module my-module gov (defcap gov () true) (defun say-hello () (do "hello world!")))
Loaded module my-module, hash Z5GCj0v6YdJTPbcc37eUYYeRiPuJGie1XFRXG16il68
pact>(list-modules)
["my-module"]

read

Use read to retrieve a row from a specified table by its key. You can optionally specify a subset of columns to return.

Basic syntax

To read an entire row from a table, use the following syntax:

pact
(read table key)
pact
(read table key)

To read specific columns from a row in a table, use the following syntax:

pact
(read table key columns)
pact
(read table key columns)

Arguments

Use the following arguments to specify the table, key, and optional columns when using the read Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table from which to read the row. In the table schema, a row represents the structure of each row in the table.
keystringSpecifies the key of the row to read from the table.
columns[string]Specifies one or more column names to return from the row. If not provided, the entire row is returned (optional).

Return values

The read function returns an object representing the requested row or columns from the specified table.

  • If you don't specify one or more columns as parameters, the function returns an object with the structure of the entire row.
  • If you specify one or more columns as parameters, the function returns an object containing only the specified columns from the row.

Examples

he following example demonstrates defining a table schema for an accounts table that stores information about bank accounts, including the balance, currency, and owner of each account:

pact
(defschema account  balance:decimal  currency:string  owner:string) (deftable accounts:{account})
pact
(defschema account  balance:decimal  currency:string  owner:string) (deftable accounts:{account})

You can then use the read function to read a row from the accounts table by its key id and retrieve only the balance and currency columns:

pact
(read accounts id ['balance 'currency])
pact
(read accounts id ['balance 'currency])

select

Use select to retrieve full rows or specified columns from a table by applying a where clause to each row to determine whether to include the row or column in the selection.

Basic syntax

To select full rows from a table based on a where clause, use the following syntax:

pact
(select table where)
pact
(select table where)

To select specific columns from a table based on a where clause, use the following syntax:

pact
(select table columns where)
pact
(select table columns where)

Arguments

Use the following arguments to specify the table, columns, and where clause for selecting rows using the select Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table from which to select rows matching the where clause.
columns[string]Specifies the list of columns to select from the table matching the where clause (optional).
whererow:object:<{row}>Specifies the where clause to apply to each row to determine inclusion.

Return value

The select function returns a list of objects representing the selected rows from the table that satisfy the where condition.

Examples

The following example demonstrates how to use the select function to select the columns 'firstName and 'lastName from the people table where the name is equal to "Fatima":

pact
(select people ['firstName 'lastName] (where 'name (= "Fatima")))
pact
(select people ['firstName 'lastName] (where 'name (= "Fatima")))

The following example demonstrates how to select all columns from the people table where the age is less than 30:

pact
(select people (where 'age (> 30)))
pact
(select people (where 'age (> 30)))

txids

Ue txids to return all of the transaction identifiers greater than or equal to a specified txid in a given table.

Basic syntax

To retrieve all transaction identifier values greater than or equal to a specified txid in a table, use the following syntax:

pact
(txids table txid)
pact
(txids table txid)

Arguments

Use the following arguments to specify the table and transaction identifier for retrieval using the txids Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table from which to retrieve transaction identifiers.
txidintegerSpecifies the transaction identifier value to compare against.

Return value

The txids function returns a list of transaction identifiers greater than or equal to the specified txid in the specified table.

Examples

The following example demonstrates how to use the txids function to retrieve all transaction identifier values greater than or equal to 123849535 in the accounts table:

pact
(txids accounts 123849535)
pact
(txids accounts 123849535)

txlog

Use txlog to return all updates made to a specified table in a particular transaction identified by its transaction identifier.

Basic syntax

To retrieve all updates made to the specified table in a specific transaction identifier, use the following syntax:

pact
(txlog table txid)
pact
(txlog table txid)

Arguments

Use the following arguments to specify the table and transaction identifier for retrieval using the txlog Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table from which to retrieve updates.
txidintegerSpecifies the transaction identifier (TXID) for which updates are to be retrieved.

Return value

The txlog function returns a list of objects representing all updates made to the specified table in the transaction identified by the txid provided.

Examples

The following example demonstrates how to use the txlog function to retrieve all updates made to the accounts table in the transaction with the 123485945 transaction identifier:

pact
(txlog accounts 123485945)
pact
(txlog accounts 123485945)

update

Use update to write an entry in the specified table for a given key with the data provided in the object column. It fails if data does not exist for the specified key.

Basic syntax

To update an entry in the specified table for a specific key with the provided object column data, use the following syntax:

pact
(update table key object)
pact
(update table key object)

Arguments

Use the following arguments to specify the table, key, and object data for updating a table using the update Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table in which to update the entry.
keystringSpecifies the key for the entry to be updated.
objectobjectSpecifies the object column data to be written for the key.

Return value

The update function returns a string indicating the success of the update operation.

Examples

The following example demonstrates how to use the update function to update an entry in the accounts table for the specified key with the provided object column data:

pact
(update accounts id { "balance": (+ bal amount), "change": amount, "note": "credit" })
pact
(update accounts id { "balance": (+ bal amount), "change": amount, "note": "credit" })

This example illustrates how to use the update function to modify an entry in a table with new data in Pact, ensuring that the operation fails if data does not exist for the specified key.

with-default-read

Use with-default-read to read a row from a specified table for a given key and bind columns according to provided bindings. If the row is not found, the function reads columns from a default object with matching key names.

Basic syntax

To read a row from a table with default values and bind columns according to the provided binding, use the following syntax:

pact
(with-default-read table key default bindings)
pact
(with-default-read table key default bindings)

Arguments

Use the following arguments to specify the table, key, defaults, bindings, and body for execution using the with-default-read Pact special form.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table from which to read the row.
keystringSpecifies the key for which to read the row.
defaultobjectSpecifies a default object containing values for missing columns.
bindingsbinding:<{row}> Specifies the bindings for columns to be bound.
bodyanySpecifies the subsequent body statements to be executed.

Return value

The with-default-read is a special form that returns the result of executing the provided body statements.

Examples

The following example demonstrates how to use the with-default-read function to read a row from the accounts table for the specified key, using default values if the row is not found, and binds the balance and currency columns for further processing:

pact
(with-default-read accounts id { "balance": 0, "currency": "USD" } { "balance":= bal, "currency":= currency }  (format "Balance for {} is {} {}" [id bal currency]))
pact
(with-default-read accounts id { "balance": 0, "currency": "USD" } { "balance":= bal, "currency":= currency }  (format "Balance for {} is {} {}" [id bal currency]))

This example illustrates reading the accounts table with the row key of id and setting default values of 0 and USD for the balance and currency columns if the row isn't found to format a default message using the format function.

with-read

Use with-read to read a row from a specified table for a given key and bind columns according to provided bindings over subsequent body statements.

Basic syntax

To read a row from a table and bind columns according to provided bindings, use the following syntax:

pact
(with-read table key bindings)
pact
(with-read table key bindings)

Arguments

Use the following arguments to specify the table, key, bindings, and body for execution using the with-read Pact special form.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table from which to read the row.
keystringSpecifies the key for which to read the row.
bindingsbinding: <{row}>Specifies the bindings for columns to be bound.
bodyanySpecifies the subsequent body statements to be executed.

Return value

The with-read is a special form returns the result of executing the provided body statements.

Examples

The following example demonstrates how to use the with-read function to read a row from the accounts table for the specified key and bind the balance and currency columns for further processing:

pact
(with-read accounts id { "balance":= bal, "currency":= ccy }  (format "Balance for {} is {} {}" [id bal ccy]))
pact
(with-read accounts id { "balance":= bal, "currency":= ccy }  (format "Balance for {} is {} {}" [id bal ccy]))

write

Use write to write the specified {column:value} object in the specified table for a given key row. The write function is similar to the insert and update functions, except that:

  • The insert function fails if data already exists for the specified key row.
  • The update function fails if data does not exist for the specified key row.

In both of these cases, the write function can succeed and update the table without failing.

Basic syntax

To write an entry in a specified table for a specific key with the provided object, use the following syntax:

pact
(write table key object)
pact
(write table key object)

Arguments

Use the following arguments to specify the table, key, and object data for writing using the write Pact function.

ArgumentTypeDescription
tabletable: <{row}>Specifies the table in which to write the entry.
keystringSpecifies the key for the entry to be written.
objectobjectSpecifies the object column data to be written for the key.

Return value

The write function returns a string indicating the success of the write operation.

Examples

The following example demonstrates how to use the write function to write an entry in the accounts table for the specified key with the provided object column data:

pact
(write accounts id { "balance": 100.0 })
pact
(write accounts id { "balance": 100.0 })

This example illustrates inserting data into the balance column in the accounts table using the id as the row key.