Query

Its possible to call query api from the applications. In this template we can create sql queries against precreated database tables.

In order to use this feature the applications needs to register access for its tables beforehand.

Create a template with type ‘query’.

Usage

The query calls can only be used from function templates and cannot be directly called from pages or routes.

{{ $res = .Tools.AppData.RunQuery "demo-app-bulk-query" }}

We can pass parameters to the query after the template name. There is no limit to the amount of parameters.

{{ $res = .Tools.AppData.RunQuery "demo-app-bulk-query" $arg1 }}

Methods

There are 2 diffrent ways to call queries: single or bulk.

  1. Single - A single query call Single queries
  2. Bulk - Contains multiple calls in a single query template, optionally the calls can be sent in a single transaction. Bulk queries

Cache

The query results can be cached using special helpers in query templates. These work for both single and bulk queries.

When used then automat will return the cached results if they exist. The second parameters is how many minutes the cache will be valid. If the cache is expired or doesn’t exist then the query will be executed and the results will be cached for future use.

{{ .SetCache 10 }}

Optionally we can also reset the cache if needed. This will do both return fresh results and reset the cache timer with the new results.

{{ .ResetCache }}

Results

Result is given as gjson.Result type. We can then read it similar to dynamic api results.

The regular query call will fail the entire template render process if the query fails. Use the new V2 method if the application requires special customer error handling for possible query or db issues.

{{ $res = .Tools.AppData.RunQuery "demo-app-single-query" }}
{{ $v := $res.Get "id" }}

Using V2 method to read the results

The V2 method returns a special structured response object. It does not fail the template parser if there are issues with the query calls.

The following call would always succeed.

{{ $res = .Tools.AppData.RunQueryV2 "demo-app-single-query" }}

{{ $res.Result }} 

Check if the request was successful

{{ $res = .Tools.AppData.RunQueryV2 "demo-app-single-query" }}

{{ if $res.IsSuccess }}
    {{ .Tools.DebugLog "ok" }}
{{ end }}

{{ $res.Result }} 

Check if there was an error and then record it where needed

{{ $res = .Tools.AppData.RunQueryV2 "demo-app-single-query" }}

{{ if $res.IsSuccess }}
    {{ .Tools.DebugLog "ok" }}
{{ end }}


{{ if $res.IsError }}
    {{ .Tools.DebugLog $r.Error }}
    {{ .Tools.AddError $r.Error }}
{{ end }}

{{ $res.Result }} 

Fetch the manual errors on the page (need to be after the function execution) When we use the .Tools.AddError to set manual errors.

<div>
    {{ range .Tools.Errors }}
        <span>{{ . }}</span>
    {{ end }}  
</div>