Skip to content

machcli

Since v8.0.75

The machcli module provides a Machbase client API for JSH applications.

Client

Creates a database client.

Syntax
new Client(config)
Configuration fields
  • host (default: 127.0.0.1)
  • port (default: 5656)
  • user (default: sys)
  • password (default: manager)
  • alternativeHost (optional)
  • alternativePort (optional)
  • database (optional): Database to use when connecting in a multi-database environment (alias db) Since v8.7.0
Usage example
1
2
const { Client } = require('machcli');
const db = new Client({ host: '127.0.0.1', port: 5656, user: 'sys', password: 'manager' });
Multi-database example

Specify database when creating the client to select the target database for the connection. db is an alias of database. Since v8.7.0

1
2
3
4
5
6
7
8
9
const { Client } = require('machcli');
const db = new Client({
  host: '127.0.0.1',
  port: 5656,
  user: 'sys',
  password: 'manager',
  db: 'MACHBASEDB',
});
const conn = db.connect();

Client.connect()

Opens a connection and returns a Connection object.

Syntax
connect()

Client.close()

Closes the underlying database client.

Syntax
close()

Client.user()

Returns the configured user name (uppercase).

Syntax
user()

Client.normalizeTableName()

Normalizes a table name into [database, user, table] format.

Syntax
normalizeTableName(tableName)

Client.tx()

Since v8.7.0

Runs fn inside a transaction on a connection acquired from the pool. If fn returns normally, the transaction is committed; if fn throws, the transaction is rolled back and the error is re-thrown. fn receives a Connection bound to the transaction, so query()/queryRow()/exec() on it participate in the same transaction.

⚠️
Transactions only work on regular tables created with CREATE TABLE. Log tables (CREATE LOG TABLE) and tag tables (CREATE TAG TABLE) do not support transactions; any exec()/query() issued inside tx() against them fails with an error such as MACHCLI-ERR-2362.
Syntax
tx(fn)
Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const { Client } = require('machcli');
const db = new Client({ host: '127.0.0.1', port: 5656, user: 'sys', password: 'manager' });
const conn = db.connect();
conn.exec('CREATE TABLE IF NOT EXISTS TX_SAMPLE (ID LONG, NAME VARCHAR(100))');

// commits automatically when fn returns normally
db.tx(function (tx) {
  tx.exec('INSERT INTO TX_SAMPLE VALUES(?, ?)', 1, 'committed');
});

// rolls back and re-throws when fn throws
try {
  db.tx(function (tx) {
    tx.exec('INSERT INTO TX_SAMPLE VALUES(?, ?)', 2, 'rolledback');
    throw new Error('abort');
  });
} catch (e) {
  console.println('rolled back:', e.message);
}
conn.close();
db.close();

Connection

Connection object returned by Client.connect().

Connection.query()

Executes a SELECT query and returns a Rows object. params can be positional arguments for ? placeholders. Or a key-value object { key: value, ... } for :key named parameters Since v8.7.0 .

Syntax
query(sql[, ...params])
Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const { Client } = require('machcli');
var db, conn, rows;
const conf = {
  host: '127.0.0.1',
  port: 5656,
  user: 'sys',
  password: 'manager' 
};
try {
  db = new Client(conf);
  conn = db.connect();

  // Positional parameters
  rows = conn.query('SELECT NAME, TIME, VALUE FROM TAG LIMIT ?', 1);
  for (const row of rows) {
    console.println(row.NAME, row.TIME, row.VALUE);
  }
  rows.close();

  // Named parameters
  rows = conn.query('SELECT NAME, TIME, VALUE FROM TAG WHERE NAME = :name ORDER BY TIME LIMIT :one', { name: 'jsh', one: 1 });
  for (const row of rows) {
    console.println(row.NAME, row.TIME, row.VALUE);
  }
  rows.close();
} catch( e ) {
  console.println("ERROR", e.message);
}
db && db.close();

Connection.queryRow()

Executes a query and returns a single row object.

Returned object includes _ROWNUM and each column as a property.

Syntax
queryRow(sql[, ...params])

Connection.exec()

Executes DDL/DML and returns result object.

Returned fields:

  • rowsAffected
  • message
Syntax
exec(sql[, ...params])

Connection.explain()

Returns an execution plan string.

Syntax
explain(sql[, ...params])

Connection.append()

Creates an appender object for bulk inserts.

The returned appender supports methods such as append(), flush(), close().

Syntax
append(tableName)
Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const { Client } = require('machcli');
const db = new Client({ host: '127.0.0.1', port: 5656, user: 'sys', password: 'manager' });
const conn = db.connect();
const appender = conn.append('TAG');
appender.append('sensor-1', new Date(), 12.34);
appender.flush();
const result = appender.close();
console.println(result);
conn.close();
db.close();

Connection.tx()

Since v8.7.0

Runs fn inside a transaction on this specific connection, the same commit/rollback semantics as Client.tx(). Use it when the transaction must run on a connection you already hold (e.g. a connection returned by Client.connect()).

⚠️
Transactions only work on regular tables created with CREATE TABLE. Log tables (CREATE LOG TABLE) and tag tables (CREATE TAG TABLE) do not support transactions; any exec()/query() issued inside tx() against them fails with an error such as MACHCLI-ERR-2362.
Syntax
tx(fn)
Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const { Client } = require('machcli');
const db = new Client({ host: '127.0.0.1', port: 5656, user: 'sys', password: 'manager' });
const conn = db.connect();
conn.exec('CREATE TABLE IF NOT EXISTS TX_SAMPLE (ID LONG, NAME VARCHAR(100))');

conn.tx(function (tx) {
  tx.exec('INSERT INTO TX_SAMPLE VALUES(?, ?)', 1, 'committed');
});

conn.close();
db.close();

Connection.close()

Closes the connection.

Syntax
close()

Rows

Result set object returned by Connection.query().

Rows.message

Message from query execution.

Rows.isFetchable()

Returns whether the result set can fetch rows.

Syntax
isFetchable()

Rows.next()

Returns an iterator result object.

  • { value: Row, done: false } while rows remain
  • { done: true } when completed
Syntax
next()

Rows.close()

Closes the result set.

Syntax
close()

Row

Represents a fetched row object.

  • Each column is available as row.COLUMN_NAME.
  • for...of iteration is supported.

queryDatabaseId()

Returns backup tablespace ID for a mounted database.

  • Returns -1 for default database ('' or MACHBASEDB).
  • Throws an error when the database is not found.
Syntax
queryDatabaseId(conn, dbName)

queryTableType()

Returns table type code by normalized table name tokens.

Syntax
queryTableType(conn, names)

TableType

stringTableType()

Table type constants and string converter.

TableType values
  • Log, Fixed, Volatile, Lookup, KeyValue, Tag
Syntax
stringTableType(type)

TableFlag

stringTableFlag()

Table flag constants and string converter.

TableFlag values
  • None, Data, Rollup, Meta, Stat
Syntax
stringTableFlag(flag)

stringTableDescription()

Returns combined table description with type and flag text.

Syntax
stringTableDescription(type, flag)

ColumnType

stringColumnType()

Column type constants and string converter.

Main ColumnType values
  • Short, UShort, Integer, UInteger, Long, ULong
  • Float, Double, Varchar, Text, Clob, Blob, Binary
  • Datetime, IPv4, IPv6, JSON
Syntax
stringColumnType(columnType)

columnWidth()

Returns default display width for a column type.

Syntax
columnWidth(columnType, length)

ColumnFlag

stringColumnFlag()

Column flag constants and string converter.

ColumnFlag values
  • TagName
  • Basetime
  • Summarized
  • MetaColumn
Syntax
stringColumnFlag(flag)
Last updated on