SCRIPT()
Syntax: SCRIPT(language, [{init_code},] {main_code})
- language : specify the script language (set
"js"
for Javascript) - init_code : initialize code (optional)
- main_code : script code
The init_code is optional and runs only once at the beginning. The main_code is mandatory and cannot be omitted.
Javascript
TQL supports the SCRIPT()
function, which utilizes JavaScript (ECMA5) in both SRC and MAP contexts
Since v8.0.36
.
This feature offers developers the flexibility to use a familiar programming language,
enhancing their ability to create more dynamic and powerful scripts within TQL.
Machbase-neo exposes the $
variable as the context object. JavaScript can access and yield records and database through this context.
$.payload
Input data of the request.$.params
Input query parameters of the request.$.key
,$.values
Javascript access point to the key and values of the current record. It is only available if theSCRIPT()
is a MAP function.$.yield()
Yield a new record with values$.yieldKey()
Yield a new record with key and values$.db()
Returns a new database connection.$.db().query()
Execute SQL query.$.db().exec()
Execute non-SELECT SQL.$.request().do()
Request HTTP to the remote server.
Caveat Emptor
use strict
does nothing.ECMA5 only. Some ES6 features e.g. Typed Arrays and back-tick string interpolation are not supported.
Regular expression is not fully compatible with the ECMA5 specification. The following regular expression syntax is incompatible:
(?=)
Lookahead (positive), it produces a parsing error(?!)
Lookahead (backhead), it produces a parsing error\1
,\2
,\3
, … Backreference, it produces a parsing error
$.payload
JavaScript can access the input data of the request using $.payload
. If there is no input data, $.payload
will be undefined
.
|
|
Call the tql file without any request body which makes the $.payload
is undefined
.
curl -o - -X POST http://127.0.0.1:5654/db/tql/test.tql
Then the result is the default values: name,0,10
.
Call the tql file with a custom data.
curl -o - -X POST http://127.0.0.1:5654/db/tql/test.tql \
-d '{"prefix":"testing", "offset":10, "limit":10}'
Then the result is: testing,10,10
$.params
JavaScript can access the request’s query parameters using $.params
.
The value of a query parameter can be accessed in two ways: using dot notation ($.params.name
)
or bracket notation ($.params["name"]
).
Both forms are interchangeable and can be used based on the context or preference.
|
|
Call the tql file without parameters.
curl -o - -X POST http://127.0.0.1:5654/db/tql/test.tql
The result will be the default values: name,0,10
.
Call the tql file with parameters.
curl -o - -X POST "http://127.0.0.1:5654/db/tql/test.tql?"\
"prefix=testing&offset=12&limit=20"
The result is: testing,12,20
.
$.key
Access the key of the current record.
This is defined only when SCRIPT
is used as a MAP function.
If SCRIPT
is used as an SRC function, it will be undefined
.
|
|
hello-1,key is 0
hello-2,key is 1
hello-3,key is 2
$.values
Access the values of the current record.
This is defined only when SCRIPT
is used as a MAP function.
If SCRIPT
is used as an SRC function, it will be undefined
.
|
|
The output is:
the first value is string,2nd value is 10,3rd is 3.14
$.yield()
Yield the new record to the next step, with the key automatically assigned as a sequentially increasing number.
$.yieldKey()
yieldKey()
functions similarly to $.yield()
, with the exception that the first argument specifies the key of the record.
$.db()
Returns a new database connection. The connection provides query()
, exec()
functions.
$.db().query()
JavaScript can query the database using $.db().query()
.
Apply a callback function with forEach()
to the return value of query()
to iterate over the query results.
If the callback function of .forEach()
explicitly returns false
, the iteration stops immediately.
If the callback function returns true
or does not return anything (which means it returns undefined
),
the iteration continues until the end of the query result.
|
|
cpu.percent,1725330085908925000,73.9
cpu.percent,1725343895315420000,73.6
cpu.percent,1725343898315887000,6.1
cpu.percent,1725343901314955000,10.8
cpu.percent,1725343904315952000,40
$.db().exec()
If the SQL is not a SELECT statement, use $.db().exec()
to execute INSERT, DELETE, CREATE TABLE statements.
|
|
$.request().do()
Syntax: $.request(url [, option]).do(callback)
Request option
{
method: "GET|POST|PUT|DELETE", // default is "GET"
headers: { "Authorization": "Bearer auth-token"}, // key value map
body: "body content if the method is POST or PUT"
}
The actual request is made when .then()
is called with a callback function to handle the response. The callback function receives a Response object as an argument, which provides several properties and methods.
Response
Property | Type | Description |
---|---|---|
.ok | Boolean | true if the status code of the response is success. (200<= status < 300 ) |
.status | Number | http response code |
.statusText | String | status code and message. e.g. 200 OK |
.url | String | request url |
.headers | Map | response headers |
The Response object provides useful methods that serves the body content of the response.
Method | Description |
---|---|
.text(callback(txt)) | Call the callback with content in a string |
.blob(callback(bin)) | Call the callback with content in a binary array |
.csv(callback(row)) | Parse the content into CSV format and call callback() for each row (record). |
Usage
$.request("https://server/path", {
method: "GET",
headers: { "Authorization": "Bearer auth-token" }
}).do( function(rsp){
console.log("ok:", rsp.ok);
console.log("status:", rsp.status);
console.log("statusText:", rsp.statusText);
console.log("url:", rsp.url);
console.log("Content-Type:", rsp.headers["Content-Type"]);
});
Examples
Hello World
SCRIPT("js", {
console.log("Hello World?");
})
DISCARD()
Result
Builtin Math object
Javascript builtin functions are available:
|
|
The equivalent result using SET-MAP functions instead of Javascript is:
|
|
JSON parser
|
|
Result
{
"data": {
"columns": [ "NAME", "AGE", "IS_MEMBER", "HOBBY" ],
"types": [ "string", "int32", "bool", "string" ],
"rows": [
[ "James", 24, true, "book,game" ]
]
},
"success": true,
"reason": "success",
"elapse": "627.958µs"
}
Fetch CSV
|
|
Fetch JSON text
This example demonstrates how to fetch JSON content from a remote server and parse it using Javascript.
|
|