Advanced Features
Use relationship queries, aggregate expressions, and remote procedure calls with the JavaScript Relational SDK.
Use a relational project with a registered web app and an initialized client. These examples assume USERS(ID, NAME) and ORDERS(ID, USER_ID, TOTAL, AMOUNT, STATUS), with a foreign key from ORDERS.USER_ID to USERS.ID. DDS Data Grants must permit the reads.
Relationship and Join Queries
Select related rows through the select() projection. The SDK uses a left join for related tables by default.
Nested Relationships
Include the related table and its projected columns inside the parent projection. The following example returns each user with related order identifiers, totals, and statuses:
const { data, error } = await client
.from("users")
.select("id,name,orders(id,total,status)");
Filtering Related Rows
Use !inner to return only parent rows that have matching related rows:
const { data, error } = await client
.from("users")
.select("id,name,orders!inner(id,total,status)");
Aggregation Functions
Use aggregate expressions inside select(). The supported aggregate functions are count, sum, avg, min, and max.
const { data, error } = await client
.from("orders")
.select(`
row_count:count(),
total:amount.sum(),
average:amount.avg(),
minimum:amount.min(),
maximum:amount.max()
`)
.single();
Calling Database Functions and Procedures (RPC)
Use rpc(fn, args?, options?) to execute a stored database function or procedure. Pass named function parameters in args.
The routine must exist in the active schema. Authorize execution through a database role assigned to the application’s DDS Data Role.
For example, have a database administrator grant execution of TESTUSER.CALCULATE_ORDER_TOTAL to the project’s unauthenticated Data Role:
CREATE ROLE app_rpc_executor;
GRANT EXECUTE ON TESTUSER.CALCULATE_ORDER_TOTAL TO app_rpc_executor;
GRANT app_rpc_executor TO "TESTUSER$NOAUTH_ROLE";
Use your project’s schema, routine, and intended Data Role. app_rpc_executor is the database role created for this privilege.
Call the function with its named parameter. This example assumes that CALCULATE_ORDER_TOTAL accepts P_ORDER_ID:
const { data, error } = await client.rpc(
"calculate_order_total",
{ p_order_id: 42 }
);
if (error) {
throw error;
}