Skip to content

Reading and Saving Table Data

Server scripts read and write the tables of relational database schemas through $Database. This page shows how to query rows, filter and summarize them with expressions, copy them to and from process data, and save changes efficiently.

Table writes are part of the operation's transaction: when the script fails, they are discarded together with the process data changes. See Error Handling and Transactions.

Reading Rows

$Database.Get runs a query and returns a DataTable. Inside Each, this is the row and columns are read as properties:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
var customers = $Database.Get({
    TargetSchema : 'Sales',
    TargetTable : 'Customers',
    Columns : [
        { Name : 'Id' },
        { Name : 'Name' },
        { Name : 'City' }
    ],
    Where : {
        Criteria : [
            { Expression : 'Active', Value : true }
        ]
    },
    Order : [
        { Expression : 'Name', Type : 'Ascending' }
    ],
    MaxLength : 50
});

customers.Each(function () {
    console.log(this.Name + ' (' + this.City + ')');
});

Without Columns, all columns of the table are returned. Use Start and MaxLength to read a page of rows. When only one column must match a value, GetData is shorter:

1
var lines = $Database.GetData('Sales', 'OrderLines', 'OrderId', $Xml.Evaluate('Id'));

Column values are converted to JavaScript values; for example, DateTime fields become DateTimeOffset objects. See Field Values in Server Scripts.

Filtering Rows

Criteria are combined with And. Use Comparison for other operators and Condition : 'Or' with Blocks to group conditions. A criterion with IgnoredValues is skipped when its value is one of the listed values, which makes form filters optional:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
var orders = $Database.Get({
    TargetSchema : 'Sales',
    TargetTable : 'Orders',
    Where : {
        Criteria : [
            { Expression : 'Amount', Value : 1000, Comparison : 'GreaterThan' },
            // skipped when the filter fields are empty
            { Expression : 'Customer.City', Value : $Xml.Evaluate('Filter/City'), IgnoredValues : [''] },
            { Expression : 'Customer.Name', Value : $Xml.Evaluate('Filter/Name'), Comparison : 'Like', IgnoredValues : [''] }
        ]
    }
});

With Like, * in the value is a wildcard; a value without a wildcard matches anywhere in the text. See QueryCriteria for all options.

Using Expressions

Columns, criteria and orders are defined with expressions. An expression can follow relations, such as Customer.Region.Name, calculate values, such as Quantity * UnitPrice, and use date and aggregate functions. Joins and grouping are created from the expressions, so the query does not describe them:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var totals = $Database.Get({
    TargetSchema : 'Sales',
    TargetTable : 'Orders',
    Columns : [
        { Name : 'Customer', Expression : 'Customer.Name' },
        { Name : 'Month', Expression : "DateTrunc('Month', OrderDate)" },
        { Name : 'Total', Expression : 'Sum(Quantity * UnitPrice)' }
    ],
    Where : {
        Criteria : [
            { Expression : "DatePart('Year', OrderDate)", Value : 2026 },
            // a criterion on an aggregate filters the groups
            { Expression : 'Sum(Quantity * UnitPrice)', Value : 10000, Comparison : 'GreaterThan' }
        ]
    },
    Order : [
        { Expression : 'Sum(Quantity * UnitPrice)', Type : 'Descending' }
    ]
});

Aggregate columns group the result by the other columns. To compare two columns, set ValueType : 'Expression', for example { Expression : 'ShipDate', Value : 'DueDate', ValueType : 'Expression', Comparison : 'GreaterThan' }.

Use Expression instead of the older Formula property. { Name : 'Amount', Formula : 'Sum' } still works, but { Name : 'Amount', Expression : 'Sum(Amount)' } is clearer and can also contain calculations. See QueryColumn.Expression and Relational Database Query for the syntax.

Copying Rows to Process Data

ExportToXml runs a query and creates a node for each row at the given path. Columns are matched to child nodes with the same name:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Data model: Order/Lines/Line with Id, Product and Quantity
$Database.ExportToXml({
    TargetSchema : 'Sales',
    TargetTable : 'OrderLines',
    Where : {
        Criteria : [
            { Expression : 'OrderId', Value : $Xml.Evaluate('Id') }
        ]
    },
    XPath : 'Lines/Line'
});

Use a Map function when the names differ. Inside it, this is the row and the argument is the new node.

Saving Process Data to a Table

ImportFromXml saves each node selected by the path as a row. Rows are matched by primary key: existing rows are updated and new rows are inserted, so running it again does not create duplicates:

1
2
3
4
5
6
7
8
$Database.ImportFromXml({
    TargetSchema : 'Sales',
    TargetTable : 'OrderLines',
    XPath : 'Lines/Line',
    Map : function (line) {
        this.OrderId = $Xml.Evaluate('Id');
    }
});

ExportToXml and ImportFromXml require a unique primary key in the table and in the data model.

Changing Rows

For a single row, AddData inserts a row and EnsureData inserts or updates the row with the given key. Both save at once:

1
2
3
4
5
6
7
8
var id = $Xml.Evaluate('Customer/Id');

$Database.EnsureData('Sales', 'Customers', 'Id', id, {
    Id : id,
    Name : $Xml.Evaluate('Customer/Name')
}, {
    CreatedAt : DateTimeOffset.now
});

The key is not copied to a new row automatically; include it in the values, as above. The last argument is applied only when a row is inserted.

For many rows, change a table in memory and call Save once. Calling AddData or EnsureData in a loop saves on every call. Use $Database.Empty to insert rows, and ToDictionary to update existing rows by key:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var contacts = $Database.Get({ TargetSchema : 'Directory', TargetTable : 'Contacts' });
var contactsById = contacts.ToDictionary('Id');

$Xml.SelectAll('Contacts/Contact', function (contact) {
    var id = contact.Evaluate('Id');

    contactsById.Ensure(id, {
        Id : id,
        DisplayName : contact.Evaluate('DisplayName')
    });
});

contacts.Save();

To delete rows, call DeleteData with a column and value, or mark rows with Delete and call Save:

1
2
3
4
5
6
7
8
9
var lines = $Database.GetData('Sales', 'OrderLines', 'OrderId', $Xml.Evaluate('Id'));

lines.Each(function () {
    if (this.Quantity === 0) {
        this.Delete();
    }
});

lines.Save();

External Databases

ExecuteQuery and ExecuteNonQuery run SQL on a database connection defined in the domain settings. The SQL is sent to the database as written, so pass values as parameters in the syntax of that database:

1
2
3
4
5
6
7
var orders = $Database.ExecuteQuery('ErpDatabase', 'select Number, Total from Orders where CustomerCode = @Customer', {
    Customer : $Xml.Evaluate('Customer/Code')
});

orders.Each(function () {
    console.log(this.Number + ': ' + this.Total);
});

The returned table is read-only; use ExecuteNonQuery to change data. Changes in an external database are not part of the operation's transaction.