DB
Using the Nile-JS SDK DB client
The db
object is used to query the database. It is designed as a tenant-aware connection pool.
When nile.tenantId
is set, the db
object will use the correct tenant’s virtual database.
query
The query
method is used to query the database. This is the main method exposed by the db
object.
Parameters
sql
: The SQL query to execute.params
: The parameters to use in the query.
Querying a shared table
All tenants and users have access to any shared tables - tables without a tenant id column.
Querying a tenant-aware table
Tenant-aware tables have a tenant id column.
If you query them without setting nile.tenantId
, this will be a cross-tenant query.
If you set nile.tenantId
, the query will run against the tenant’s virtual database.
When inserting data into a tenant-aware table, you need to provide the tenant id - and it has to belong to an existing tenant.
If you set nile.tenantId
, the tenant id must match the tenant id in the table.
In the example below, we also use parameter substitution to prevent SQL injection.
client
The client
method is used to get a client from the database connection pool. This can be useful if you want to run several queries on the same connection.
The client is not automatically released back to the pool after the query is executed. You need to call client.release()
to release it back to the pool.
Example
The example below uses client
to run a transaction - a group of queries that are executed as a single unit.
If any of the queries fail, the transaction is rolled back.
If all queries succeed, the transaction is committed.
The client
object guarantees that all queries are executed on the same connection.
It is then released back to the pool after the transaction is committed or rolled back.