OrientJS driver

Official orientdb driver for node.js. Fast, lightweight, uses the binary protocol.

Build Status

Supported Versions

OrientJS aims to work with version 2.0.0 of OrientDB and later. While it may work with earlier versions, they are not currently supported, pull requests are welcome!

IMPORTANT: OrientJS does not currently support OrientDB’s Tree Based RIDBag feature because it relies on making additional network requests. This means that by default, the result of e.g. JSON.stringify(record) for a record with up to 119 edges will be very different from a record with 120+ edges. This can lead to very nasty surprises which may not manifest themselves during development but could appear at any time in production. There is an open issue for this in OrientDB, until that gets fixed, it is strongly recommended that you set RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD to a very large value, e.g. 2147483647. Please see the relevant section in the OrientDB manual for more information.

Installation

Install via npm.

  1. npm install orientjs

To install OrientJS globally use the -g option:

  1. npm install orientjs -g

Running Tests

To run the test suite, first invoke the following command within the repo, installing the development dependencies:

  1. npm install

Then run the tests:

  1. npm test

Features

  • Tested with latest OrientDB (2.0.x and 2.1).
  • Intuitive API, based on bluebird promises.
  • Fast binary protocol parser.
  • Distributed Support
  • Access multiple databases via the same socket.
  • Migration support.
  • Simple CLI.
  • Connection Pooling

Table of Contents

Configuring the Client

  1. var OrientDB = require('orientjs');
  2. var server = OrientDB({
  3. host: 'localhost',
  4. port: 2424,
  5. username: 'root',
  6. password: 'yourpassword'
  7. });
  1. // CLOSE THE CONNECTION AT THE END
  2. server.close();

Use JWT

  1. var server = OrientDB({
  2. host: 'localhost',
  3. port: 2424,
  4. username: 'root',
  5. password: 'yourpassword',
  6. useToken: true
  7. });

Distributed Support (experimental)

Since orientjs 2.1.11

You can pass paramenter servers to specify the OrientDB distributed instances to be used in case of connection error on the primary host. The only requirement is that at the first connection one of these server have to be online. Then orientjs will keep updated the list of the servers online in the cluster thanks to the push notification that OrientDB send to the connected clients when the shape of the cluster changes.

  1. var OrientDB = require("orientjs");
  2. var server = OrientDB({
  3. host: '10.0.1.5',
  4. port: 2424,
  5. username: 'root',
  6. password: 'root',
  7. servers : [{host : '10.0.1.5' , port : 2425}]
  8. });
  9. var db = server.use({
  10. name: 'GratefulDeadConcerts',
  11. username: 'admin',
  12. password: 'admin'
  13. });

Server API

Listing the databases on the server

  1. server.list()
  2. .then(function (dbs) {
  3. console.log('There are ' + dbs.length + ' databases on the server.');
  4. });

Creating a new database

  1. server.create({
  2. name: 'mydb',
  3. type: 'graph',
  4. storage: 'plocal'
  5. })
  6. .then(function (db) {
  7. console.log('Created a database called ' + db.name);
  8. });

Database API

Using an existing database

  1. var db = server.use('mydb');
  2. console.log('Using database: ' + db.name);
  3. // CLOSE THE DB SESSION AT THE END
  4. db.close();

If you want to close also the connection you can

  1. db.close().then(function(){
  2. // CLOSE THE CONNECTION
  3. server.close();
  4. })

Using an existing database with credentials

  1. var db = server.use({
  2. name: 'mydb',
  3. username: 'admin',
  4. password: 'admin'
  5. });
  6. console.log('Using database: ' + db.name);
  7. // CLOSE THE CONNECTION AT THE END
  8. db.close();

Using standalone db object without Server

Since orientjs 2.1.11

  1. var ODatabase = require('orientjs').ODatabase;
  2. var db = new ODatabase({
  3. host: 'localhost',
  4. port: 2424,
  5. username : 'admin',
  6. password : 'admin',
  7. name : 'GratefulDeadConcerts'});
  8. db.open().then(function(){
  9. return db.query('select from v limit 1');
  10. }).then(function(res){
  11. console.log(res.length);
  12. // this will send a db close command and then close the connection
  13. db.close().then(function(){
  14. console.log('closed');
  15. });
  16. });

Record API

Loading a record by RID.

  1. db.record.get('#1:1')
  2. .then(function (record) {
  3. console.log('Loaded record:', record);
  4. });

Deleting a record

  1. db.record.delete('#1:1')
  2. .then(function () {
  3. console.log('Record deleted');
  4. });

Class API

Listing all the classes in the database

  1. db.class.list()
  2. .then(function (classes) {
  3. console.log('There are ' + classes.length + ' classes in the db:', classes);
  4. });

Creating a new class

  1. db.class.create('MyClass')
  2. .then(function (MyClass) {
  3. console.log('Created class: ' + MyClass.name);
  4. });

Creating a new class that extends another

  1. db.class.create('MyOtherClass', 'MyClass')
  2. .then(function (MyOtherClass) {
  3. console.log('Created class: ' + MyOtherClass.name);
  4. });

Getting an existing class

  1. db.class.get('MyClass')
  2. .then(function (MyClass) {
  3. console.log('Got class: ' + MyClass.name);
  4. });

Updating an existing class

  1. db.class.update({
  2. name: 'MyClass',
  3. superClass: 'V'
  4. })
  5. .then(function (MyClass) {
  6. console.log('Updated class: ' + MyClass.name + ' that extends ' + MyClass.superClass);
  7. });

Listing properties in a class

  1. MyClass.property.list()
  2. .then(function (properties) {
  3. console.log('The class has the following properties:', properties);
  4. });

Adding a property to a class

  1. MyClass.property.create({
  2. name: 'name',
  3. type: 'String'
  4. })
  5. .then(function () {
  6. console.log('Property created.')
  7. });

To add multiple properties, pass an array of objects. Example:

  1. MyClass.property.create([{
  2. name: 'name',
  3. type: 'String'
  4. }, {
  5. name: 'surname',
  6. type: 'String'
  7. }])
  8. .then(function () {
  9. console.log('Property created.')
  10. });

Deleting a property from a class

  1. MyClass.property.drop('myprop')
  2. .then(function () {
  3. console.log('Property deleted.');
  4. });

Renaming a property on a class

  1. MyClass.property.rename('myprop', 'mypropchanged');
  2. .then(function () {
  3. console.log('Property renamed.');
  4. });

Creating a record for a class

  1. MyClass.create({
  2. name: 'John McFakerton',
  3. email: 'fake@example.com'
  4. })
  5. .then(function (record) {
  6. console.log('Created record: ', record);
  7. });

Listing records in a class

  1. MyClass.list()
  2. .then(function (records) {
  3. console.log('Found ' + records.length + ' records:', records);
  4. });

Index API

Create a new index for a class property

  1. db.index.create({
  2. name: 'MyClass.myProp',
  3. type: 'unique'
  4. })
  5. .then(function(index){
  6. console.log('Created index: ', index);
  7. });

Get entry from class property index

  1. db.index.get('MyClass.myProp')
  2. .then(function (index) {
  3. index.get('foo').then(console.log.bind(console));
  4. });

Query

Execute an Insert Query

  1. db.query('insert into OUser (name, password, status) values (:name, :password, :status)',
  2. {
  3. params: {
  4. name: 'Radu',
  5. password: 'mypassword',
  6. status: 'active'
  7. }
  8. }
  9. ).then(function (response){
  10. console.log(response); //an Array of records inserted
  11. });

Execute a Select Query with Params

  1. db.query('select from OUser where name=:name', {
  2. params: {
  3. name: 'Radu'
  4. },
  5. limit: 1
  6. }).then(function (results){
  7. console.log(results);
  8. });
Raw Execution of a Query String with Params
  1. db.exec('select from OUser where name=:name', {
  2. params: {
  3. name: 'Radu'
  4. }
  5. }).then(function (response){
  6. console.log(response.results);
  7. });

Query Builder

Creating a new, empty vertex

  1. db.create('VERTEX', 'V').one()
  2. .then(function (vertex) {
  3. console.log('created vertex', vertex);
  4. });

Creating a new vertex with some properties

  1. db.create('VERTEX', 'V')
  2. .set({
  3. key: 'value',
  4. foo: 'bar'
  5. })
  6. .one()
  7. .then(function (vertex) {
  8. console.log('created vertex', vertex);
  9. });

Deleting a vertex

  1. db.delete('VERTEX')
  2. .where('@rid = #12:12')
  3. .one()
  4. .then(function (count) {
  5. console.log('deleted ' + count + ' vertices');
  6. });

Creating a simple edge between vertices

  1. db.create('EDGE', 'E')
  2. .from('#12:12')
  3. .to('#12:13')
  4. .one()
  5. .then(function (edge) {
  6. console.log('created edge:', edge);
  7. });

Creating an edge with properties

  1. db.create('EDGE', 'E')
  2. .from('#12:12')
  3. .to('#12:13')
  4. .set({
  5. key: 'value',
  6. foo: 'bar'
  7. })
  8. .one()
  9. .then(function (edge) {
  10. console.log('created edge:', edge);
  11. });

Deleting an edge between vertices

  1. db.delete('EDGE', 'E')
  2. .from('#12:12')
  3. .to('#12:13')
  4. .scalar()
  5. .then(function (count) {
  6. console.log('deleted ' + count + ' edges');
  7. });

Insert Record

  1. db.insert().into('OUser').set({name: 'demo', password: 'demo', status: 'ACTIVE'}).one()
  2. .then(function (user) {
  3. console.log('created', user);
  4. });

Update Record

  1. db.update('OUser').set({password: 'changed'}).where({name: 'demo'}).scalar()
  2. .then(function (total) {
  3. console.log('updated', total, 'users');
  4. });

Delete Record

  1. db.delete().from('OUser').where({name: 'demo'}).limit(1).scalar()
  2. .then(function (total) {
  3. console.log('deleted', total, 'users');
  4. });

Select Records

  1. db.select().from('OUser').where({status: 'ACTIVE'}).all()
  2. .then(function (users) {
  3. console.log('active users', users);
  4. });
  1. db.select().from('OUser').containsText({name: 'er'}).all()
  2. .then(function (users) {
  3. console.log('found users', users);
  4. });

Select Records with Fetch Plan

  1. db.select().from('OUser').where({status: 'ACTIVE'}).fetch({role: 5}).all()
  2. .then(function (users) {
  3. console.log('active users', users);
  4. });

Select an expression

  1. db.select('count(*)').from('OUser').where({status: 'ACTIVE'}).scalar()
  2. .then(function (total) {
  3. console.log('total active users', total);
  4. });

Traverse Records

  1. db.traverse().from('OUser').where({name: 'guest'}).all()
  2. .then(function (records) {
  3. console.log('found records', records);
  4. });

Return a specific field

  1. db
  2. .select('name')
  3. .from('OUser')
  4. .where({status: 'ACTIVE'})
  5. .column('name')
  6. .all()
  7. .then(function (names) {
  8. console.log('active user names', names.join(', '));
  9. });

Transform a field

  1. db
  2. .select('name')
  3. .from('OUser')
  4. .where({status: 'ACTIVE'})
  5. .transform({
  6. status: function (status) {
  7. return status.toLowerCase();
  8. }
  9. })
  10. .limit(1)
  11. .one()
  12. .then(function (user) {
  13. console.log('user status: ', user.status); // 'active'
  14. });

Transform a record

  1. db
  2. .select('name')
  3. .from('OUser')
  4. .where({status: 'ACTIVE'})
  5. .transform(function (record) {
  6. return new User(record);
  7. })
  8. .limit(1)
  9. .one()
  10. .then(function (user) {
  11. console.log('user is an instance of User?', (user instanceof User)); // true
  12. });

Specify default values

  1. db
  2. .select('name')
  3. .from('OUser')
  4. .where({status: 'ACTIVE'})
  5. .defaults({
  6. something: 123
  7. })
  8. .limit(1)
  9. .one()
  10. .then(function (user) {
  11. console.log(user.name, user.something);
  12. });

Put a map entry into a map

  1. db
  2. .update('#1:1')
  3. .put('mapProperty', {
  4. key: 'value',
  5. foo: 'bar'
  6. })
  7. .scalar()
  8. .then(function (total) {
  9. console.log('updated', total, 'records');
  10. });

Transaction Builder

Transaction builder help you create batch script that will run on the server as a sigle transaction.

  1. db.let('first',function(f){
  2. f.create('vertex','V')
  3. .set({ name : 'John'})
  4. })
  5. .let('second',function(s){
  6. s.create('vertex','V')
  7. .set({ name : 'John'})
  8. })
  9. .let('edge' , function(e){
  10. e.create('edge','E')
  11. .from('$first')
  12. .to('$second')
  13. .set({ when : new Date()})
  14. })
  15. .commit()
  16. .return('$edge')
  17. .all()
  18. .then(function(res){
  19. console.log(res);
  20. })

Batch Script without Transaction Builder

Function API

You can create a function by supplying a plain javascript function. Please note that the method stringifies the function passed so you can’t use any varaibles outside the function closure.

  1. db.createFn("nameOfFunction", function(arg1, arg2) {
  2. return arg1 + arg2;
  3. })
  4. .then(function (count) {
  5. // Function created!
  6. });

You can also omit the name and it’ll default to the Function#name

  1. db.createFn(function nameOfFunction(arg1, arg2) {
  2. return arg1 + arg2;
  3. })
  4. .then(function (count) {
  5. // Function created!
  6. });

Events

You can also bind to the following events

beginQuery

Given the query

  1. db.select('name, status').from('OUser').where({"status": "active"}).limit(1).fetch({"role": 1}).one();

The following event will be triggered

  1. db.on("beginQuery", function(obj) {
  2. // => {
  3. // query: 'SELECT name, status FROM OUser WHERE status = :paramstatus0 LIMIT 1',
  4. // mode: 'a',
  5. // fetchPlan: 'role:1',
  6. // limit: -1,
  7. // params: { params: { paramstatus0: 'active' } }
  8. // }
  9. });

endQuery

After a query has been run, you’ll get the the following event emitted

  1. db.on("endQuery", function(obj) {
  2. // => {
  3. // "err": errObj,
  4. // "result": resultObj,
  5. // "perf": {
  6. // "query": timeInMs
  7. // }
  8. // }
  9. });

CLI

An extremely minimalist command line interface is provided to allow databases to created and migrations to be applied via the terminal.

To be useful, OrientJS requires some arguments to authenticate against the server. All operations require the password argument unless the user is configured with an empty password. For operations that involve a specific db, include the dbname argument (with dbuser and dbpassword if they are set to something other than the default).

You can get a list of the supported arguments using orientjs --help.

  1. -d, --cwd The working directory to use.
  2. -h, --host The server hostname or IP address.
  3. -p, --port The server port.
  4. -u, --user The server username.
  5. -s, --password The server password.
  6. -n, --dbname The name of the database to use.
  7. -U, --dbuser The database username.
  8. -P, --dbpassword The database password.
  9. -?, --help Show the help screen.

If it’s too tedious to type these options in every time, you can also create an orientjs.opts file containing them. OrientJS will search for this file in the working directory and apply any arguments it contains. For an example of such a file, see test/fixtures/orientjs.opts.

Note: For brevity, all these examples assume you’ve installed OrientJS globally (npm install -g orientjs) and have set up an orientjs.opts file with your server and database credentials.

Database CLI Commands.

Listing all the databases on the server.

  1. orientjs db list

Creating a new database

  1. orientjs db create mydb graph plocal

Destroying an existing database

  1. orientjs db drop mydb

Migrations

OrientJS supports a simple database migration system. This makes it easy to keep track of changes to your orientdb database structure between multiple environments and distributed teams.

When you run a migration command, OrientJS first looks for an orient class called Migration. If this class doesn’t exist it will be created. This class is used to keep track of the migrations that have been applied.

OrientJS then looks for migrations that have not yet been applied in a folder called migrations. Each migration consists of a simple node.js module which exports two methods - up() and down(). Each method receives the currently selected database instance as an argument.

The up() method should perform the migration and the down() method should undo it.

Note: Migrations can incur data loss! Make sure you back up your database before migrating up and down.

In addition to the command line options outlined below, it’s also possible to use the migration API programatically:

  1. var db = server.use('mydb');
  2. var manager = new OrientDB.Migration.Manager({
  3. db: db,
  4. dir: __dirname + '/migrations'
  5. });
  6. manager.up(1)
  7. .then(function () {
  8. console.log('migrated up by one!')
  9. });

Listing the available migrations

To list all the unapplied migrations:

  1. orientjs migrate list

Creating a new migration

  1. orientjs migrate create my new migration

creates a file called something like m20140318_200948_my_new_migration which you should edit to specify the migration up and down methods.

Migrating up fully

To apply all the migrations:

  1. orientjs migrate up

Migrating up by 1

To apply only the first migration:

  1. orientjs migrate up 1

Migrating down fully

To revert all migrations:

  1. orientjs migrate down

Migrating down by 1

  1. orientjs migrate down 1

Troubleshooting

  • Node exception Maximum call stack size exceeded here

History

In 2012, Gabriel Petrovay created the original node-orientdb library, with a straightforward callback based API.

In early 2014, Giraldo Rosales made a whole host of improvements, including support for orientdb 1.7 and switched to a promise based API.

Later in 2014, codemix refactored the library to make it easier to extend and maintain, and introduced an API similar to nano. The result is so different from the original codebase that it warranted its own name and npm package. This also gave us the opportunity to switch to semantic versioning.

In June 2015, Orient Technologies company officially adopted the Oriento driver and renamed it as OrientJS.

Notes for contributors

Please see CONTRIBUTING.

Changes

See CHANGELOG

License

Apache 2.0 License, see LICENSE