Parameters
format |
string | Result shape: a root name then one typed column per SQL field, as `name:type` or `@name:type` (`@` = XML attribute, otherwise element). Types such as `long`, `string`, `datetime`, `timestamp`, `memo`. |
query |
string | SQL statement with placeholders. |
dataSource |
string | Datasource name. Empty string or omitted uses the default database. |
...values |
any | Values of the placeholders, in order. |
Returns
| object | An E4X XML collection β iterate rows with `for each`, not as an array. |
Examples
Get SQL records (via SELECT) from the Adobe Campaign database. To write data, use π sqlExec.
Prefer π queryDef for simple needs: it works from the schema, enforces access rights, and is portable across database engines. sqlSelect bypasses all three (raw SQL, engine-specific, no rights check), so reach for it only when a query canβt be expressed with queryDef, such as: DISTINCT, aggregates, system tables.
Not sure what to choose between Workflow, queryDef API and sqlSelect? Read the Database article.
Format
The sqlSelect call is called with:
-
The XML shape of the result, with a root name followed by one typed columns, i.e.
"delivery, @id:long, @contact:datetime"- The first token (
delivery) names the repeating row element. - Each
name:typemaps one SQL column (a leading@makes it an XML attribute) - The type is a full word (
long,string,datetime,memo), distinct from the$()token used to bind values.
- The first token (
-
The SQL query with field names & placeholders
- Fields like
iOptionIdandsName. The prefix encodes the type (iinteger,sstring). Find them in Configure list for a schema, or via Transition > right-click > Open > Schema for a workflow temporary table. - Typed placeholders like
$(l)and$(sz)(linteger,szstring)
- Fields like
- The arguments list, in the same order as the placeholders
Get a recipient
Cast the number before it enters the query string:
var id = parseInt(recipientId, 10); // sqlSelect binds no value: cast the number yourself
if (isNaN(id)) {
logError("Invalid recipient id " + recipientId);
}
var xml = sqlSelect(
"recipient, @id:long, @email:string, @firstName:string, @lastName:string",
"SELECT iRecipientId, sEmail, sFirstName, sLastName FROM NmsRecipient WHERE iRecipientId = " + id
);
var recipients = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements(); // E4X to DOM
if (recipients.length === 0) {
logError("No recipient with id " + id);
}
var rcp = recipients[0];
logInfo(rcp.$firstName + " " + rcp.$lastName);Get a list of deliveries
var xml = sqlSelect(
"delivery, @id:long, @contact:datetime",
"SELECT iDeliveryId, tsContact FROM NmsDelivery WHERE iState = 0"
);
var deliveries = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements(); // E4X to DOM
deliveries.forEach(function (d) {
logInfo(d.$id + " contacted on " + d.$contact);
});Identifiers and engine-specific SQL
A placeholder binds a value, not a table or column name. Upgrade scripts build the table name into the string ("SELECT ... FROM " + vars.tableName) because an identifier canβt be bound. That is safe only because vars.tableName is a workflow temporary-table name produced by AC, not external input; apply the same trust test to your own code.
Raw SQL also ties you to one SQL engine. Stock code reading SQL Server system views:
var res = sqlSelect(
"result, name:string",
"SELECT name FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID(N'NmsRtEventStat')"
);
will not run on PostgreSQL. That portability cost is the main reason to prefer queryDef.
Unit tests
Tested with acc by running
acc instance exec -f test/integration/sqlSelect.spec.js in a sandbox:
loadLibrary("/nl/core/shared/nl.js"); // import NL.assert
// This unit test is PostgreSQL only. Each query executes a simple SQL statement and checks the result.
// Small helper to run a test in a try/catch and store the result in the context object
function test(name, fn) {
try {
context[name] = NL.assert(fn());
} catch (e) {
context[name] = "KO " + e;
}
}
test("test1_version", function () {
const xml = sqlSelect("pg, @version:string", "SELECT version()");
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements(); // E4X to DOM
return records.length === 1 && records[0].$version.indexOf("PostgreSQL") === 0;
});
test("test2_uptime", function () {
const xml = sqlSelect("pg, @started:datetime", "SELECT pg_postmaster_start_time()");
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements();
return (
records.length === 1 &&
parseTimeStamp(records[0].$started).getTime() <= getCurrentDate().getTime()
);
});
test("test3_database_size", function () {
const xml = sqlSelect(
"db, @name:string, @sizeMb:double",
"SELECT current_database(), pg_database_size(current_database()) / 1024.0 / 1024.0"
);
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements();
return records.length === 1 && records[0].$name !== "" && parseFloat(records[0].$sizeMb) > 0;
});
test("test4_table_count", function () {
const xml = sqlSelect("n, @count:long", "SELECT count(*) FROM pg_class WHERE relkind = 'r'");
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements();
return records.length === 1 && parseInt(records[0].$count, 10) > 0;
});
test("test5_settings", function () {
const xml = sqlSelect(
"setting, @name:string, @value:string",
"SELECT name, setting FROM pg_settings WHERE name = 'max_connections'"
);
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements();
return records.length === 1 && parseInt(records[0].$value, 10) > 0;
});
test("test6_database_statistics", function () {
const xml = sqlSelect(
"db, @name:string",
"SELECT datname FROM pg_stat_database WHERE datname = current_database()"
);
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements();
return records.length === 1 && records[0].$name !== "";
});
test("test7_sessions", function () {
// the session running this test is always counted
const xml = sqlSelect(
"session, @state:string, @count:long",
"SELECT coalesce(state, 'none'), count(*) FROM pg_stat_activity WHERE datname = current_database() GROUP BY 1"
);
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements();
var total = 0;
records.forEach(function (record) {
total += parseInt(record.$count, 10);
});
return records.length >= 1 && total >= 1;
});
test("test8_transaction_age", function () {
const xml = sqlSelect(
"db, @name:string, @age:long",
"SELECT datname, age(datfrozenxid) FROM pg_database"
);
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements();
return (
records.length >= 1 &&
records.every(function (record) {
return parseInt(record.$age, 10) >= 0;
})
);
});
test("test9_biggest_tables", function () {
const xml = sqlSelect(
"table, @name:string, @sizeMb:double",
"SELECT relname, pg_total_relation_size(oid) / 1024.0 / 1024.0 FROM pg_class WHERE relkind = 'r' ORDER BY pg_total_relation_size(oid) DESC LIMIT 5"
);
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements();
return records.length >= 1 && records.length <= 5 && parseFloat(records[0].$sizeMb) > 0;
});
test("test10_default_data_source", function () {
// an empty data source is the default database: same result as no argument
const xml = sqlSelect("pg, @version:string", "SELECT version()", "");
const records = DOMDocument.fromXMLString(xml.toXMLString()).root.getElements();
return records.length === 1 && records[0].$version.indexOf("PostgreSQL") === 0;
});See also
-
π sqlExec- Run a SQL query for advanced needs. Prefer using workflow activities ("Update Data"). -
π queryDef- Helper to run a SQL SELECT query with JSON and returns an XML element.