node-cubrid
This is a Node.js driver for CUBRID open-source relational database.
node-cubrid is implemented in 100% JavaScript with no external dependency (except the
development dependencies). Besides the database specific APIs, the module supplies several
helper APIs which are useful to sanitize and validate user input values, format and
parametrize SQL statements, etc.
Table of Contents
Key features
- Full compatibility with CUBRID 8.4.1+ releases.
- Rich database support: Connect, Query, Fetch, Execute, Execute in batch, Commit, Rollback, etc.
- Support for queries queueing.
- Support for database schema.
- Support for database parameters and transactions.
- Support for LOB (Binary and Character) objects.
- Support for ENUM data types since CUBRID 9+.
- Fully implements the event emitter.
- Extensive tests suite (90% code coverage).
- Full
Promise support since v3.0.0.
CHANGELOG
Refer to https://github.com/CUBRID/node-cubrid/releases tab.
Installation
Since v3.0.0 the driver requires Node >=v4. If you are on an older version of Node,
you can use the previous node-cubrid v2.2.5.
npm install node-cubrid
This will install the latest version available at https:* www.npmjs.com/package/node-cubrid.
Once installed, the module can be accessed by requiring the node-cubrid module:
const CUBRID = require('node-cubrid');
The node-cubrid module exports the following properties and functions:
Helpers: an object which provides a set of helper functions.
createConnection() (alias createCUBRIDConnection()): a function which returns a new client connection object to work with a user defined CUBRID host and database.
createDefaultCUBRIDDemodbConnection(): a function which returns a connection object to work with a local demodb database.
Request flow in node-cubrid
When the request is sent to the server, CUBRID executes it, and returns the response, which can be either a query result set, or the error code. It is by design that CUBRID does not return any identification about the request sender. In other words, in order to associate the response with a request, the driver has to have only one active request which can be the only owner of this response.
For this reason, if a developer wants to execute several queries, they must execute them one after another, i.e. sequentially, NOT in parallel. This is how the communication between the driver and the server is implemented in CUBRID and most other database systems including MySQL.
If there is a vital need to run queries in parallel, developers can use connection pooling modules. An example with this technique is provided below.
API Documentation
Creating a CUBRID client
/*
* `createCUBRIDConnection()` function accepts either an object or a list of
* connection parameters. The following list of parameters are supported:
* 1. `hosts`: Can be either:
* - a string representing an IP or a domain name of the CUBRID host
* (without the `http://` part)
* - (since 3.0.0) an array of strings like
* `['host1[:port1]', 'host2[:port2]', ...]`.
*
* When a custom `port` is not specified, the driver will use the
* default `port` specified by the user when creating a connection.
* When a user has not specified the default `port`, it defaults to
* `33000`.
*
* Defaults to `localhost`.
* 2. `port`: a port CUBRID is listening to. Defaults to `33000`.
* 3. `user`: the database username. Defaults to `public`.
* 4. `password`: the database user password. Defaults to an empty string.
* 5. `database`: the name of a database to connect to. Default to `demodb`.
* 7. `connectionTimeout`: the timeout value in milliseconds for the connection.
* If `connectionTimeout = 0`, it will wait until the network socket times out
* itself. Defaults to `0`.
* 8. `maxConnectionRetryCount`: the number of times the connection needs to
* be retried in case of failure. Defaults to `1`. Since `3.0.0`.
* 9. `logger`: a custom logger that implements at least `debug` and `info`
* functions. Defaults to noop (nothing will be logged). For more details
* refer to **Logging** section below. Since `3.0.0`.
*/
// All arguments are optional in which case default values will be set.
var client = CUBRID.createCUBRIDConnection(host, port, user, password, database, connectionTimeout);
* Alias function since version 2.1.0.
var client = CUBRID.createConnection(host, port, user, password, database, connectionTimeout);
// Alternatively, an object of parameters can be passed. Since version 2.1.0.
var client = CUBRID.createConnection(paramsObject);
The following example shows how to create a client by providing an object of connection parameters.
const client = CUBRID.createConnection({
host: host,
port: port,
user: user,
password: password,
database: database,
connectionTimeout: connectionTimeout,
maxConnectionRetryCount: maxConnectionRetryCount,
logger: logger
});
Establishing a connection
// callback(err) function receives one arguments: the error message if any.
const promise = client.connect(callback);
Callback style
The code below illustrates a callback style when a function is passed as an argument
to a connect() API which is called after the module receives a response from CUBRID.
const CUBRID = require('node-cubrid');
const dbConf = {
host: 'localhost',
port: 33000,
user: 'public'
password: '',
database: 'demodb'
};
const client = CUBRID.createConnection(dbConf);
client.connect(function (err) {
if (err) {
throw err;
} else {
console.log('connection is established');
client.close(function (err) {
if (err) {
throw err;
} else {
console.log('connection is closed');
}
});
}
});
Promise style
Alternatively, a Promise style is supported. For example, the above code can be rewritten as:
client
.connect()
.then(() => {
console.log('connection is established');
return client.close();
})
.catch(err => {
throw err;
});
Implicit connection
node-cubrid performs an implicit connection whenever necessary. When you execute a query
on a client without explicitly establishing a connection by calling client.connect(), the
driver will automatically establish a connection before executing your query.
Connection errors
There can be several reasons for a connection to fail:
Connection configuration
Setting connection timeout
// Both functions are available since version 2.0.0.
const timeoutInMilliseconds = client.getConnectionTimeout();
// Set connection timeout in milliseconds.
client.setConnectionTimeout(2000);
// Alternatively, set the connection timeout value at client creation time.
// Available since version 2.1.0.
var client = CUBRID.createConnection(host, port, user, password, database, connectionTimeout);
One of the requests we have got for the 2.0 driver release was to implement a connection
timeout feature. Simply said - wait for the connection to the database to complete within
the specified number of seconds and eventually throw an error if the timeout occurs.
Obviously, the key thing here was to set the connection timeout at the Node.js socket
connection layer level (and not on the consumer level):
this._socket = Net.createConnection(hostInfo.port, hostInfo.host);
this._socket.setNoDelay(true);
this._socket.setTimeout(this.getConnectionTimeout());
In node-cubrid by default the connection timeout value is set to 0, i.e.
the driver will wait long enough until the underlying network socket times out itself.
In this case, according to our observations, the timeout event is emitted in about
75 seconds (purely observational point).
So, if you want or expect the connection to timeout within the specified time, then
manually set the timeout value as shown below.
const client = new CUBRIDConnection(dbConf.host, dbConf.port, dbConf.user, dbConf.password, dbConf.database, /* connectionTimeout */ 2000);
// Or at runtime.
client.setConnectionTimeout(2000);
client.connect(function (err) {
if (err) {
console.log(err);
}
client.close();
});
As you see, the timeout is specified in milliseconds 2000, which is 2 seconds.
After 2 seconds, the script will timeout with an error like:
{ [Error: connect ETIMEDOUT] }
Setting CUBRID Server Parameters
// Both functions are available since version 2.0.0.
client.getDatabaseParameter(paramType);
client.setDatabaseParameter(paramType, paramValue);
After connecting to a database, a user can override some global session parameters
that will control the behavior queries being executed. For example, isolation level
of transactions, the auto-commit behavior, etc.
The complete list of these CUBRID database parameters is defined in the
Constants.js file:
/**
* Define CUBRID Database parameters constants
*/
exports.CCIDbParam = {
CCI_PARAM_ISOLATION_LEVEL : 1,
CCI_PARAM_LOCK_TIMEOUT : 2,
CCI_PARAM_MAX_STRING_LENGTH : 3,
CCI_PARAM_AUTO_COMMIT : 4
};
For each parameter, the CUBRID communication protocol implements a dedicated support for GET
and SET operations. Therefore, in order to manipulate them, also a dedicate functionality was
needed in the driver and this is what we did in the 2.0 release.
Please note one exception - the CCI_PARAM_MAX_STRING_LENGTH parameter cannot be set
programmatically from code as it is a CUBRID Broker parameter and the client can only query
its current value.
Let’s see some examples. First, let set the value of the ISOLATION_LEVEL parameter:
const CAS = require('./node_modules/node-cubrid/src/constants/CASConstants');
client.connect(function (err) {
// handle error, then...
client.setDatabaseParameter(CAS.CCIDbParam.CCI_PARAM_ISOLATION_LEVEL, CAS.CUBRIDIsolationLevel.TRAN_REP_CLASS_COMMIT_INSTANCE, function (err) {
// handle error
CUBRIDClient.close(function (err) {
// …
});
});
});
And let’s see how we can retrieve the value of the LOCK_TIMEOUT parameter for the current session:
client.connect(function (err) {
client.getDatabaseParameter(CAS.CCIDbParam.CCI_PARAM_LOCK_TIMEOUT, function (err, value) {
// handle error, then...
console.log('LOCK_TIMEOUT is: %s', value);
CUBRIDClient.close(function (err) {
// ...
});
});
});
The output result is:
LOCK_TIMEOUT is: -1
Note: The same value can be obtained also from CUBRID Manager Client:
If you need to change the default values for these parameters, it is highly recommended
to do it immediately after connect ().
Executing SQL queries
READ queries