Your own databases: Qubix.db
Qubix.db is the command through which a user script and a website page handler work with your own database: they read data and write changes. Which databases it connects to — in the Which databases section. No HTTP middleman is needed for this — the script connects to the database itself, with a connection string or by the name of a saved connection.
This is not the Qubix database. The statistics Qubix records are read by the sql command — read-only and within the rights of your role (see Tables for sql queries). Qubix.db works with your database with the rights of the database user named in the connection string — it both reads and writes.
Where the command is available:
- in scripts of the Scripts section — both on a schedule and via the Executar button;
- in landing page handlers — on every visit and via the Executar button in the Executor de teste panel (see Landing page backend).
Britva rules do not have Qubix.db.
You can connect only to a host that an administrator has entered in the Hosts de bancos de dados para scripts list (Configurações do Qubix → JavaScript). While the list is empty, connections to databases are off. More — in the Where you can connect section.
Which databases
| Database | The connection string starts with | Port when none is given | A value's place in the query text |
|---|---|---|---|
| PostgreSQL | postgres:// or postgresql:// | 5432 | $1, $2… |
| MySQL, MariaDB | mysql:// or mariadb:// | 3306 | ? |
| MS SQL Server | sqlserver:// | 1433 | @p1, @p2… |
| ClickHouse | clickhouse://; clickhouses:// — encrypted, with a certificate check | 8123; 8443 for clickhouses:// | {p1:Type}, {p2:Type}… — for example {p1:UInt64} |
All of them work as the rest of this article describes: query returns rows, exec — the number of changed rows. A ClickHouse value cannot be null — write NULL in the query text instead; and a read-only ClickHouse user needs readonly=2, not readonly=1: every query sends its own settings, and readonly=1 forbids them.
What it looks like
function main() {
const db = Qubix.db.connect('postgres://report:[email protected]:5432/crm')
const rows = db.query('SELECT id, email FROM customers WHERE country = $1 LIMIT 10', ['DE'])
for (const row of rows) console.log(row.id, row.email)
const changed = db.exec('UPDATE customers SET checked_at = now() WHERE country = $1', ['DE'])
console.log('rows changed:', changed)
db.close()
}
All calls are synchronous: the result comes right away, as with sql and ctx.fetch, so await is not needed. With the other databases everything is the same, except for the start of the string and the way a value's place is marked in the query text — see Which databases.
Connection string
Qubix.db.connect(...) takes a string of this form:
postgres://user:password@host:5432/database?sslmode=require
mysql://user:password@host:3306/database?tls=true
| Part | What it means |
|---|---|
| scheme | the kind of database — see Which databases |
user:password@ | the database user and their password. What the queries may do is decided by this user's rights in your database |
host | one host — a name or an address. Several hosts separated by commas are not accepted, and neither is a path to a socket file instead of a host: the connection goes over the network only |
:port | optional; without a port — the port from the Which databases table |
/database | the database name |
?… | parameters — only from the table below |
The connection string is read by the rules of an address, so characters like #, ?, /, % or a space in the user name and the password must be written in percent-encoding. The easiest way is to build the string with encodeURIComponent:
const url = 'postgres://report:' + encodeURIComponent(password) + '@db.example.com:5432/crm'
String parameters:
| Parameter | Database | Values | If not given |
|---|---|---|---|
sslmode | PostgreSQL | disable, allow, prefer, require, verify-ca, verify-full | prefer: an encrypted channel if the database supports it, otherwise an open one |
channel_binding | PostgreSQL | disable, prefer, require | prefer |
require_auth | PostgreSQL | scram-sha-256 — the password goes only by SCRAM: a server that asks for it in any other way gets a refusal | whatever the server asks for |
application_name | PostgreSQL | any name — the connection shows up under it in the database's list of connections | — |
tls | MySQL, MariaDB | true — encryption with certificate verification; skip-verify — encryption without certificate verification; preferred — encryption without verification if the server supports it, otherwise an open channel; false — no encryption | no encryption |
encrypt | MS SQL Server | strict — encryption with certificate and name verification; true — encryption without certificate verification; false — only the login is encrypted; disable — no encryption | encryption without verification if the server supports it, otherwise an open channel |
app name | MS SQL Server | any name — the connection shows up under it on the server | — |
ClickHouse takes no parameters: an encrypted channel is chosen by the scheme — clickhouses://.
Other parameters are not accepted — the refusal lists the supported ones. Parameters that would make the connection read files on the Qubix server — for example sslrootcert for PostgreSQL or allowAllFiles for MySQL — are always rejected.
A string without :// is the name of a saved connection: the call opens the connection saved under this name in the Secrets panel, and a name that is not there gets a refusal — see Saved connections.
When the server reaches the internet through Tor
If an administrator set the server to reach the internet through Tor (the Requisições de saída tab), a database on the internet is connected only when the connection checks the database server by its name: set sslmode=verify-full for PostgreSQL, tls=true for MySQL and MariaDB, encrypt=strict for SQL Server; write a ClickHouse address as clickhouses://; for a saved connection choose Criptografar e verificar o certificado in the Criptografia (SSL/TLS) field. A Tor exit is somebody else's server: without the check it would receive the database password. sslmode=verify-ca is not enough — without a root certificate of your own it accepts any public certificate without checking the name — and neither is channel_binding=require with require_auth=scram-sha-256: the password does not travel open then, but an exit that accepted the encryption itself gets enough to guess a weak password offline. A database on an internal network from the host list is reached directly, and the rule does not apply to it.
Saved connections
A connection can be saved once under a name, and the code then opens it by that name. The password is not written in the code, and neither scripts nor other people can see it:
function main() {
const db = Qubix.db.connect('crm')
try {
const rows = db.query('SELECT id, email FROM customers LIMIT 10')
console.log('rows:', rows.length)
} finally {
db.close()
}
}
Everything else works as with a connection string: the same query, exec and close, the same host list, limits and refusals.
Connections are kept in the Secrets panel. It opens from the script editor — the item of the same name in the "…" menu of the script's header (its tooltip says Ações) — and from the handler editor on the Backend tab of a site card — the button with a database icon in the top row of the open handler, next to Salvar.
Shared and Mine
The panel has two tabs:
- Compartilhadas — available to every script and every page handler. They are added and edited by those whose role has the Gerenciar credenciais de serviços permission (an administrator has it always); everyone else sees only the name and the type of a shared connection and cannot open it.
- Minhas — your own connections. They are available to your scripts and the handlers of your websites. Besides you, the code of your script and of your website's handlers can be changed only by an administrator, and through such code they use your connections without seeing the password. One person keeps up to 20 connections of their own.
Under the tabs a hint says what is kept there. On Compartilhadas: Available to all code and to tables from external databases. In fact the hint names only one of those who may: shared connections are added and edited by everyone whose permission template grants the Gerenciar credenciais de serviços right, and an administrator has it always. On Minhas: Available only to your code and your tables from external databases. Anyone allowed to edit your code or such a table can use your secrets through them, without seeing the values.
The panel keeps more than connections: its list is one for every kind of saved secret. The columns are Nome, Type (Database connection, Address key) and Details. For a database connection the details are the type of the database, the host with the port and the database name, and the user. For an address key — the end of the key and, when requests to the address are closed, a red line; see A saved key for an address.
Adding a connection
- Open the panel, choose the tab, click Adicionar and choose Database connection.
- Fill in the fields:
- Nome — small Latin letters, digits,
_and-, up to 64 characters. The code opens the connection by this name; once the connection is saved, the name can no longer be changed. The name must be unique within the tab. Under the field: Os scripts abrem a conexão por este nome: Qubix.db.connect("crm"). - Tipo de banco de dados — PostgreSQL, MySQL / MariaDB, MS SQL Server or ClickHouse.
- Host — a host name or an IP address.
- Porta — leave it empty to use the type's port from the Which databases table; for ClickHouse with Criptografar e verificar o certificado or Criptografar sem verificar o certificado it is 8443.
- Banco de dados, Usuário and Senha. Under the password field: Armazenada criptografada: nem os scripts nem outras pessoas conseguem vê-la. Uma senha salva não pode ser visualizada, apenas substituída.
- Criptografia (SSL/TLS) — see below; a new connection starts with Criptografar se o banco de dados for compatível. Under the field: Protege a senha e os dados no caminho até o banco de dados. «Criptografar e verificar o certificado» aceita apenas um certificado emitido por uma autoridade publicamente confiável, como nos sites https: um certificado autoassinado ou emitido pela sua própria autoridade certificadora não será aceito. Um banco de dados sem criptografia se conecta com «Criptografar se o banco de dados for compatível» e com «Não criptografar», e a senha então trafega em texto simples.
- Nome — small Latin letters, digits,
- Click Testar a conexão to check the connection: the panel answers Conectado or Não foi possível conectar: … — the dots stand for the reason.
- Click Salvar.
The check goes through the same host list as a real connection and under the limits of the editor the panel was opened from. A host that is not on the list gets Host "…" is not in the "Database hosts for scripts" list (Qubix settings → Work tools → JavaScript)., and a name from the list that leads to an internal network gets Address blocked: requests to the internal network are not allowed.
Encryption
| Mode | What it does |
|---|---|
| Criptografar e verificar o certificado | encrypts the channel and accepts only a certificate issued by a publicly trusted authority, as on https websites: a self-signed certificate or one issued by your own certificate authority will not pass |
| Criptografar sem verificar o certificado | encrypts the channel without checking the certificate |
| Criptografar se o banco de dados for compatível | encrypts if the database supports encryption; otherwise the connection goes unencrypted |
| Não criptografar | does not encrypt |
A database without encryption connects only with the last two modes, and the password then travels in plain text. When the server reaches the internet through Tor, a database on the internet connects only with Criptografar e verificar o certificado — see above.
The saved password
A saved password cannot be viewed, only replaced. When you edit a connection, leave the password field empty to keep the saved one. The saved password goes only to the same server — the same database type, host and port — and never over weaker encryption: change any of the three or lower the encryption, and the panel asks for the password again: the field becomes required, and the hint under it reads Digite a senha novamente: uma senha salva é enviada apenas ao mesmo servidor e nunca por meio de uma criptografia mais fraca. The modes from the weakest to the strongest: Não criptografar, Criptografar se o banco de dados for compatível, Criptografar sem verificar o certificado, Criptografar e verificar o certificado.
Which connection a name opens
Qubix.db.connect('crm') looks for the name first among Minhas and then among Compartilhadas, so a personal connection hides a shared one of the same name. Whose Minhas are searched depends on where the code runs:
- a script — those of the script's owner, both on a schedule and with the Executar button; a built-in script looks only among Compartilhadas;
- a page handler — those of the website's owner on a live visit, and those of whoever pressed Executar in the Executor de teste panel.
Capital Latin letters in the name are read as small ones: connect('CRM') opens crm. If the owner is switched off or deleted, a name from their Minhas is refused and is not passed on to a shared connection of the same name.
Deleting a connection
Excluir is in the form of an open connection. A connection whose name is written in quotes — "crm", 'crm' or `crm` — in the code of a script or a page handler is not deleted, a switched-off script included: the refusal names those that use it, as far as you can see them. For a connection from Minhas, only your own scripts and the handlers of your websites count. A connection whose stored record could not be read is listed by its name only and cannot be opened; it has its own Excluir link in its row.
Queries: query and exec
Qubix.db.connect(...) returns a connection object:
| Method | What it does | What it returns |
|---|---|---|
query(text, params) | runs a query that returns rows | an array of rows; each row is an object whose keys are the column names |
exec(text, params) | runs a changing statement: INSERT, UPDATE, DELETE and others | the number of rows the statement changed |
close() | closes the connection | nothing |
Values are passed separately from the query text — as the second argument, in an array, while the text marks their places the way the database expects (the table in Which databases). A value is not pasted into the query text, so you do not need to escape it by hand, and the query cannot be tampered with through it. The second argument can be left out if there are no values.
| Value in JavaScript | How it goes to the database |
|---|---|
a string, a number, true / false, null | as is |
Date | a date and time |
ArrayBuffer | binary data |
| an array, an object | not accepted — a refusal. For a JSON column, pass JSON.stringify(value) |
What comes back in the answer rows:
| Column in the database | Value in the answer row |
|---|---|
| integer | a number. An integer beyond JavaScript's exact integer range (Number.MAX_SAFE_INTEGER) comes as a string, so that no digits are lost |
floating-point (real, double precision, FLOAT, DOUBLE) | a number |
decimal (numeric, DECIMAL) | a string — this way no precision is lost |
| JSON | a string — parse it with JSON.parse |
date (DATE) | a string like 2026-09-27 |
| date and time | a string in ISO format in UTC, for example 2026-09-27T10:00:00Z |
binary (bytea, BLOB) | ArrayBuffer |
boolean (boolean in PostgreSQL) | true / false. In MySQL BOOLEAN is the integer TINYINT, so it comes as the number 0 or 1 |
NULL | null |
| anything else | a string |
Date-and-time columns without a time zone (timestamp in PostgreSQL, DATETIME in MySQL) carry no zone in the value itself: the time comes as it was written, with a Z appended.
Columns with the same name — for example, id from two tables — give one property in the row, and the last one stays. Give them different names with AS.
Closing the connection
close() closes the connection. Calling it again breaks nothing, and a query over a closed connection gets a refusal. A connection you did not close is closed on its own: for a script — right after the run, for a page handler — before the answer to the visitor. Close the connection as soon as you no longer need it — most conveniently in a finally block.
All queries of one connection go in one database session: the connection is not swapped for another one in the middle of a run. Closing does not give back a place in the connection limit — every attempt to connect to a host during a run counts.
Example: a summary from Qubix statistics into your own database
The script counts the deposits of the past day by country with the sql command — the way the panel's reports count them, above the deposit threshold — and writes the result into your PostgreSQL table with a single insert.
function main() {
const rows = sql`
WITH (SELECT threshold FROM v_deposits_min_revenue) AS dep_min
SELECT country, sumIf(if(edition = 'cancel', -1, 1), event = 'dep' AND revenue_usd > dep_min) AS deps
FROM qubix_events
WHERE event_time > now() - INTERVAL 1 DAY
AND country != ''
GROUP BY country`
if (!rows.length) return
// One insert for all rows: every query and exec call counts toward the query limit.
const values = []
const params = []
for (const r of rows) {
values.push('(now(), $' + (params.length + 1) + ', $' + (params.length + 2) + ')')
params.push(r.country, r.deps)
}
const db = Qubix.db.connect('postgres://writer:[email protected]:5432/reports')
try {
const inserted = db.exec('INSERT INTO daily_deps (taken_at, country, deps) VALUES ' + values.join(', '), params)
console.log('rows written:', inserted)
} finally {
db.close()
}
}
For another database, mark the values its own way — see Which databases. Split a large volume into several inserts, but not into an insert per row: you will run into the query limit.
Where you can connect
You can connect only to a host from the Hosts de bancos de dados para scripts list. An administrator maintains the list on the JavaScript tab of the Configurações do Qubix window — the tab itself is described in the System article. There is one list for scripts and website page handlers; while it is empty, connections to databases are off.
Entries are written one per line:
| Entry | What it opens |
|---|---|
a name, for example db.example.com | this host — but only if the name leads to an address on the internet |
an address, for example 10.0.0.5, or a network, for example 10.0.0.0/24 | this address or this network, including on an internal network; after that the database can also be reached by a name that leads to this address |
* | any address on the internet, but not the internal network |
Enter a database on an internal network — yours or the Qubix server's own — as an address or a network: a name alone is not enough for it. An entry that could not be read (for example, a network with a wrong mask) is skipped, and a line about it goes to the server log. A change to the list takes effect from the next run, no restart needed.
Limits
An administrator sets the limits on the same JavaScript tab. For scripts they sit under the host list and are counted per run. Website page handlers have limits of their own — in the Handlers de páginas de sites (Locations) block: connections and queries there are counted per page request, while the rows, the answer size and the timeout are labeled the same way as for scripts.
| Limit | What it restricts | What happens beyond it |
|---|---|---|
| Bancos de dados: máx. conexões por execução (for handlers — Bancos de dados: máx. conexões por requisição de página) | the number of connections: every attempt to connect to a host counts, including a failed one; a call rejected earlier — with an empty host list or a list without a single readable entry, or with a value that is not a string or is longer than 8 KB — does not count, while a wrong connection string and the name of a connection that is not saved do count | a refusal |
| Bancos de dados: máx. consultas por execução (for handlers — Bancos de dados: máx. consultas por requisição de página) | the number of query and exec calls across all connections together | a refusal |
| Bancos de dados: máx. linhas por consulta | the number of rows in the answer to one query | the extra rows are not read: the database stops the query, query returns the first rows, and a warning goes to the run log |
| Bancos de dados: tamanho máx. da resposta | the size of the database's answer to one query. Every byte received counts, the service ones included, so the limit is reached sooner than the sum of the values themselves would reach it | a refusal. A PostgreSQL, MySQL or MS SQL Server connection is closed after it, a ClickHouse connection stays usable |
| Bancos de dados: timeout de consulta | the time of one query and of one connection attempt | a refusal. A MySQL connection is closed after it, the others stay usable |
Besides these limits, queries are stopped by the overall deadline: the script's run time, or Máx. tempo de execução do handler for a page handler. A change to the limits takes effect from the next run.
Refusals and what to do about them
A refusal is an ordinary JavaScript error. You can catch it with try…catch and carry on. An uncaught error stops the script's run with an error, and a page handler answers the visitor with an empty 500 response; to see the reason, repeat the request in the Executor de teste panel (see Landing page backend).
The refusal texts are in English. The tables below leave out the common prefix Qubix.db: that most of them start with. The host list and the limits are named in the texts the way they are labeled in the English interface; N in a text stands for a number.
Connecting and the host list
| Refusal | What happened | What to do |
|---|---|---|
connections to databases are off: the "Database hosts for scripts" list (Qubix settings → Work tools → JavaScript) is empty | the host list is empty | ask an administrator to enter the database host |
connections to databases are off: … has no entry that can be read (see the server log) | the list has no entry that could be read | for an administrator — fix the entries; the unread ones are named in the server log |
host "db.example.com" is not in the "Database hosts for scripts" list (Qubix settings → Work tools → JavaScript) | the host is not on the list | enter the host: a name — for a database on the internet, an address or a network — for a database on an internal network |
host "db.example.com" is on an internal network: its address or network must be in the "Database hosts for scripts" list (Qubix settings → Work tools → JavaScript) | the name is on the list but leads to an internal address | enter the database's address or network in the list |
host "db.example.com" has no address, host "db.example.com" could not be resolved | no address was found for a name from the list | check the host name |
Qubix.db.connect("crm"): there is no saved connection with this name (the «Secrets» window of the code editor) | no connection is saved under this name | check the name in the Secrets panel or pass a connection string |
Qubix.db.connect("crm"): the saved connection is a personal one of an account that is disabled, removed or gone; it is not opened | the name is among the personal connections of an owner who is switched off or deleted | save the connection under Compartilhadas or pass a connection string |
Qubix.db.connect("crm"): the saved connection could not be read; see the server log | the stored record of the connection could not be read | for an administrator — the reason is in the server log |
database type "oracle" is not supported (postgres://, mysql://, sqlserver://, clickhouse://) | an unknown scheme | start the string with one of the schemes the text names |
one host per connection, the connection string names no host, port "…" is not a number from 1 to 65535, cannot read the connection string; its details are withheld, as they could carry the password — … | the connection string is put together wrong; in the last case it is a user name or password with characters written as is that an address does not take there (/, ?, #, %, a space, ^, ` | , brackets, letters other than Latin — build them with encodeURIComponent), a port that is not a number, or an @after the host written as is (in the database name or a parameter write it as%40`) — and the text does not quote the string, so as not to show the password |
cannot read the parameters of the connection string; its details are withheld, as a password may be among them — … | a parameter value has a % that is not the start of a percent-encoded character, or a ; | write % and ; in parameter values percent-encoded |
parameter "foo" is not supported (supported: …), sslmode="bogus" is not supported (supported: …), parameter "…" is given more than once | a parameter not from the list, a wrong value or a repeat | keep the parameters from the table above, each one only once |
this server reaches the internet through Tor, and a Tor exit reads a connection that does not check the database server… | the server reaches the internet through Tor, and the connection does not check the database server | do what the end of the text says: for a connection string it names what to add, for a saved connection — the Criptografar e verificar o certificado mode; see above |
parameter "sslrootcert" is not allowed: it makes the driver read files on the server | the parameter would make the connection read files on the Qubix server | remove the parameter |
host "/var/run/postgresql" is a unix socket; only TCP connections are allowed, parameter "host" is not allowed: … | instead of a host, the address has a socket path, or the host is given in the parameters | give the host and the port in the address itself |
Limits and timeout
For a page handler, the text says per page request instead of per run.
| Text | What happened | What to do |
|---|---|---|
connection cap exceeded: N per run (limit "Databases: max connections per run") | the connection limit is used up | open one connection and run all queries through it |
query cap exceeded: N per run (limit "Databases: max queries per run") | the query limit is used up | combine queries: many rows — in one insert, many reads — in one query |
the answer is larger than N bytes (limit "Databases: max response size, bytes") | the answer is larger than the limit; the connection is closed | select fewer columns and rows; open a new connection for the next queries |
the answer has more than N values (rows × columns for a table, elements for a document or array): one value per 8 bytes of the limit "Databases: max response size, bytes" | the answer holds more values than the response-size limit allows — one per 8 bytes | narrow the selection: fewer columns, a WHERE condition, LIMIT, aggregation |
the database sent more than N bytes while connecting (limit "Databases: max response size, bytes") | the database sent too much already while logging in | check that it is really a database that answers at this address and port, and that the answer size limit is not too small |
query stopped after N ms (limit "Databases: query timeout, ms") | the query or the connection attempt did not fit into the time limit | speed up the query or ask an administrator to raise the limit |
this connection was closed after an answer exceeded the response cap, this connection was closed after a query ran out of time | the connection was closed after one of the refusals above | open a new connection |
the run is out of time; the query was stopped | the run time of the script or the handler is over | cut down the work that one run does |
result truncated to N rows (the “Databases: max rows per query” limit in the “External databases (Qubix.db)” group of the JavaScript settings is N) | this is not a refusal but a warning in the run log, and it comes in the language of the panel: there are more rows than the limit, the first ones came back. For a page handler the text names the “Website page handlers (Locations)” group | narrow the selection: a WHERE condition, LIMIT, aggregation in the query |
Values and calls
| Text | What happened |
|---|---|
this connection is closed | a query over a connection already closed with close() |
parameter #2 is an array; pass a string, number, boolean, null, Date or ArrayBuffer | the value is an array |
parameter #2 is an object; pass JSON.stringify(value) for a JSON column | the value is an object |
query(text, params): params must be an array, e.g. [42, "text"] | the values were not passed as an array |
Qubix.db.connect(connection): pass a connection string such as postgres://user:password@host:5432/database | something other than a string was passed to Qubix.db.connect |
Answers from the database itself
Everything else is your database's answer: a wrong password, no such table, an error in the query text. It follows Qubix.db: together with the explanations the connection adds: for example, with a wrong password in PostgreSQL the text contains failed SASL auth: FATAL: password authentication failed for user "report". The password from the connection string does not get into the text, and the addresses the host leads to are replaced with its name.
Script and website page handler: the differences
| Script | Website page handler | |
|---|---|---|
| When it runs | on a schedule and via the Executar button | on every visit and via the Executar button in the Executor de teste panel |
| Limits | counted per run; the fields under the host list | counted per page request; the Handlers de páginas de sites (Locations) block |
| Refusal on a limit | … per run | … per page request |
| Warning about truncated rows | in the run console | only in the test run console: the log of a live visit is not shown anywhere |
| Overall deadline | the script's run time | Máx. tempo de execução do handler |
| Unclosed connections | are closed right after the run | are closed before the answer to the visitor |
| Whose Minhas a saved name opens | the script owner's | the website owner's; on a test run — of whoever pressed Executar |
| Connection reuse | no: every run opens its own connections | no: every visit opens its own connections, and the database login repeats on every page view |
| Uncaught refusal | the run ends with an error | the visitor gets an empty 500 response |
| The visitor left without waiting for the answer | — | the handler is interrupted, and the running database query is canceled: the change it was making may or may not get applied |
Your own Qubix name at the top level of the code | the save is refused: the name is taken by the platform | the handler works, but Qubix.db is unavailable to it |
If the handler has not returned even after its deadline, the visitor gets a 503 response, and the connections of this run are closed when the handler finally finishes.
Every page view logs in to the database anew, so keep handler queries short and do not open more than one connection where one is enough.
Both the Executar button of a script and the Executar button of a handler run real queries against your database: changes made through exec are applied at once. Test writes on a test table or a test database.