Custom queries
Introduction
The data endpoints cover filtering, sorting and joining one table at a time. When you need more — reports with GROUP BY, several joins, subqueries — you can send your own SQL SELECT to StellarDS.io. You write it with the table and field names you see in the database designer; StellarDS.io checks it, runs it against your project only and returns the rows as JSON.
Custom queries are read-only. They can't change data or the structure of your tables.
Availability
| Plan | Custom queries | Time limit | Rows per result | Procedures |
|---|---|---|---|---|
| Free | not included | |||
| Basic | not included | |||
| Pro | yes | 20 seconds | 10,000 | 10 |
| Ultimate | yes | 60 seconds | 50,000 | 50 |
At most two custom queries can run at the same time per project. Every query counts as one request towards your plan's monthly request limit.
Running a query
Send a POST to /v1/data/query?project={projectId} with the query and, optionally, values for its parameters:
curl -X POST "https://api.stellards.io/v1/data/query?project=3fa85f64-5717-4562-b3fc-2c963f66afa6" \
-H "Authorization: Bearer {access_token}" \
-H "Content-Type: application/json" \
-d '{
"query": "select c.Name, count(o.id) as orders from Customers c left join Orders o on o.CustomerId = c.id where c.Company = @company group by c.Name",
"parameters": { "company": "Globex" }
}'
If you prefer the project in the path, POST /v1/project/{projectId}/query does the same.
The response lists the columns in order and one object per row:
{
"data": {
"columns": [ { "name": "Name", "type": "nvarchar" }, { "name": "orders", "type": "int" } ],
"rows": [ { "Name": "Ada", "orders": 3 }, { "Name": "Grace", "orders": 1 } ],
"count": 2,
"truncated": false,
"durationMs": 12
},
"messages": [],
"isSuccess": true
}
When a result has more rows than your plan allows, you get the first rows and truncated is true. Add a WHERE, TOP or OFFSET ... FETCH to page through large results.
When two columns have the same name (for example c.id and o.id), the second one is returned as id_2. Columns without a name are called column1, column2 and so on; give them a name with AS.
From .NET
var result = await sdk.Data.QueryAsync(projectId,
"select Name, Email from Customers where Company = @company order by Name",
new { company = "Globex" });
foreach (var row in result.Data!.Rows)
Console.WriteLine($"{row["Name"]} <{row["Email"]}>");
Checking a query without running it
The query editor in the console completes table, field and function names as you type (press Ctrl+Space to ask for them) and underlines problems before you run anything. Your own tools can do the same with two endpoints. Neither counts against your plan's request limit.
POST /v1/data/query/validate?project={projectId} checks a query the way running it would, and also reports field names a table doesn't have. Pass the names of the parameters the query may use:
{
"query": "select c.Nmae from Customers c where c.Company = @company",
"parameters": [ "company" ]
}
{
"data": {
"valid": false,
"problems": [
{ "message": "Table 'Customers' has no field 'Nmae'. Did you mean 'Name'?", "line": 1, "column": 8 }
]
},
"messages": [],
"isSuccess": true
}
A problem about the query as a whole has line and column 0. GET /v1/data/query/schema?project={projectId} returns the tables you can read with their fields (id first, blob fields left out) and the functions a query may call. In .NET, use sdk.Data.ValidateQueryAsync and sdk.Data.GetQuerySchemaAsync. With the project in the path, the routes are /v1/project/{projectId}/query/validate and /v1/project/{projectId}/query/schema.
Writing queries
- Use the table and field names from the designer. Every table also has an
idfield. Put names with spaces or special characters between brackets:select [Unit price] from [Order lines]. - A query is one
SELECTstatement. You can useJOIN(inner, left, right, full, cross),WHERE,GROUP BY(includingROLLUPandCUBE),HAVING,ORDER BY,TOP,OFFSET ... FETCH,DISTINCT,UNION/EXCEPT/INTERSECT, subqueries,EXISTS,IN,LIKE,BETWEEN,CASEand common table expressions (WITH x AS (...), not recursive). - Use parameters (
@name) for values that come from your users, and pass them inparameters. Never paste user input into the query text. - You can use these functions:
| Kind | Functions |
|---|---|
| Aggregates | COUNT, COUNT_BIG, SUM, AVG, MIN, MAX |
| Text | LEN, LOWER, UPPER, LTRIM, RTRIM, TRIM, LEFT, RIGHT, SUBSTRING, REPLACE, CHARINDEX, CONCAT, CONCAT_WS, REVERSE, STUFF, REPLICATE |
| Dates | GETUTCDATE, SYSUTCDATETIME, DATEADD, DATEDIFF, DATEPART, DATENAME, YEAR, MONTH, DAY, EOMONTH, DATEFROMPARTS |
| Numbers | ABS, ROUND, CEILING, FLOOR, POWER, SQRT, SIGN |
| Other | ISNULL, COALESCE, NULLIF, IIF, CAST, CONVERT, TRY_CAST, TRY_CONVERT |
CAST and CONVERT accept the number, text (up to 8000 characters), date/time, bit and uniqueidentifier types.
Not supported
- Anything that changes data or tables (
INSERT,UPDATE,DELETE,CREATE,DROP,SELECT INTO, ...), and more than one statement per query. - Blob fields. Download those with the blob endpoint.
- Window functions (
OVER),APPLY, table hints,OPTION,FOR JSON/FOR XML, variables other than your parameters, and system functions or views. - Tables from other projects. Only the tables of the project in the request exist for the query.
Procedures
A procedure is a custom query you save in the project under a name, with typed parameters, so apps can run it without sending SQL. It can have up to 10 steps; each step is a SELECT and returns its own result, and can use values from earlier steps. All steps run together within the plan's time limit.
Saving a procedure
Members with the permission to create tables can manage procedures (GET, POST /v1/procedures?project={projectId}, GET, PUT, DELETE /v1/procedures/{name}?project={projectId}) or use Procedures in the application. Every procedure route also exists with the project in the path: /v1/project/{projectId}/procedures and /v1/project/{projectId}/procedures/{name}.
{
"name": "CustomerReport",
"description": "A customer and their larger orders",
"parameters": [
{ "name": "customer", "type": "bigint", "required": true },
{ "name": "minimum", "type": "float", "defaultValue": "0" }
],
"steps": [
{ "name": "customer", "sql": "select Name, Email from Customers where id = @customer" },
{ "name": "orders", "sql": "select id, Total, OrderedOn from Orders where CustomerId = @customer and Total >= @minimum order by OrderedOn desc" }
]
}
- Names use letters, digits and underscores.
- Parameter types:
int,bigint,decimal,float,bit,nvarchar(n)(up to 4000),date,datetime2,uniqueidentifier. An optional parameter without a value uses itsdefaultValue, orNULL. - Every step is checked when you save, so a stored procedure always worked when it was saved. If a table or field it uses is renamed or deleted later,
problemsin the procedure lists what broke. - Each save increases
version. Send theversionyou edited withPUTto get a409instead of overwriting someone else's newer changes.
Using values from an earlier step
A step can use a value from the first row of an earlier step as @step_column: the step name, an underscore and the column name as that step's result shows it.
"steps": [
{ "name": "customer", "sql": "select id, Company from Customers where Email = @email" },
{ "name": "orders", "sql": "select id, Total from Orders where CustomerId = @customer_id order by OrderedOn desc" },
{ "name": "colleagues", "sql": "select Name from Customers where Company = @customer_Company and id <> @customer_id" }
]
- The value has the type of the column and is passed as a parameter, just like your own parameters.
- If the earlier step returns no rows, the value is
NULL. If it returns several, the first one counts, so useorder by(ortop 1) to pick it. - Only earlier steps can be used. A procedure parameter with the same name wins over a step value.
- Names are checked when you save. If
@order_line_idcould mean columnline_idof steporderor columnidof steporder_line, the save is refused; rename a step or give the column an alias.
Running a procedure
Any member of the project can run it with POST /v1/procedures/{name}/execute?project={projectId} (or POST /v1/project/{projectId}/procedures/{name}/execute):
{ "parameters": { "customer": 42, "minimum": 100 } }
var report = await sdk.Procedures.ExecuteAsync(projectId, "CustomerReport", new { customer = 42, minimum = 100 });
var orders = report.Data!.Results.Single(r => r.Step == "orders").Rows;
A procedure runs with the rights of the caller, exactly like a custom query: they need permission to read records of every table any step uses, and multi-tenant rows are filtered for them. A missing required parameter, or a value that doesn't fit its type, returns 400 with the parameter named.
Permissions and multi-tenant projects
A query or procedure runs with the rights of whoever sends it. The caller needs permission to read records of every table the query uses; otherwise the request is refused with 403 and the table is named.
In a multi-tenant project (or multi-tenant table), users only see their own rows, exactly as with the data endpoints. Members with the See every tenant's records permission see every row.
Access tokens and apps
Access tokens and OAuth apps can run queries and procedures too. They get the permissions of the role you gave them: to read records of a table, the role needs that permission on the table, and to manage procedures, the role needs the permission to create tables. An access token isn't a user, so in multi-tenant tables it only sees rows that were written with an access token, unless its role has See every tenant's records. An OAuth app acts for the user who signed in through it and sees that user's rows.
Errors
| Status | Meaning |
|---|---|
400 |
The query isn't allowed or isn't valid. Every problem is listed with its line and column, for example Line 1, column 15: Unknown table 'Invoice'. Did you mean 'Invoices'? Also returned when the query took longer than the time limit, was estimated to be too expensive, or failed while running. |
401 |
No valid access token. |
403 |
Your plan doesn't include custom queries, or you can't read one of the tables. |
429 |
Too many custom queries are running for this project at the same time. Try again shortly. |
Errors about values that can't be converted (for example CAST('abc' AS int)) don't show the value itself.