Git Product home page Git Product logo

orientjs's Introduction

OrientJS driver

Official orientdb driver for node.js. Fast, lightweight, uses the binary protocol. REUSE status npm version npm downloads

NOTE: Release v3.0 provides new APIs in order to support OrientDB 3.0 features.

Features

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

Versions and Compatibility

OrientJS v3.0 contains backwards compatible APIs for OrientDB 2.2.x and OrientDB 3.0.x using the old protocol version 33 (Legacy). New APIs are shipped in v3.0 to support the new protocol featuring Streaming, Stateful transactions, new SQL engine etc..

Resources

Installation

Install via npm.

npm install orientjs

For Typescript usage :

npm install @types/orientjs

Quick Start

Connect to OrientDB

Use the connect function in order to create a new OrientDBClient instance.

const OrientDBClient = require("orientjs").OrientDBClient;

OrientDBClient.connect({
  host: "localhost",
  port: 2424
}).then(client => {
  return client.close();
}).then(()=> {
   console.log("Client closed");
});

Single Session

To open a new standalone session use the client.session api. This api will create a new stateful session associated with the given database and credentials. Once done, call session.close in order to release the session on the server. Session are stateful since OrientJS 3.0 as they can execute server side transactions.

client.session({ name: "demodb", username: "admin", password: "admin" })
.then(session => {
	// use the session
	... 
	// close the session
	return session.close();
});

Pooled Sessions

Opening and closing sessions everytime can be expensive, since open and close require a network request to the server. Use the API client.sessions to create a pool of sessions with a given database and credentials. To get a session from the pool call the api pool.acquire. Once done with the session you can return the session to the pool by calling session.close

// Create a sessions Pool
client.sessions({ name: "demodb", username: "admin", password: "admin", pool: { max: 10} })
  .then(pool => {
    // acquire a session
    return pool.acquire()
      .then(session => {
        // use the session
        ...
        // release the session
        return session.close();
      })
      .then(() => {
      	 // close the pool
        return pool.close();
      });
  });
});

Session API

Once obtained a session using the above APIs you can:

  • Run a Query (Idempotent SQL statement)
  • Run a Command (Idempotent or non idempotent SQL statement)
  • Run a Transaction
  • Run a live query

Query

Streaming

session.query("select from OUser where name = :name", {params: { name: "admin" }})
.on("data", data => {
	console.log(data);
})
.on('error',(err)=> {
  console.log(err);
})
.on("end", () => {
	console.log("End of the stream");
});

or use .all API that convert the stream to a Promise and collect the result set into an array

session.query("select from OUser where name = :name", { params : {name: "admin" }})
.all()
.then((results)=> {
	console.log(results);
});

Command

session.command("insert into V set name = :name", {params: { name: "test" }})
.all()
.then(result => {
	console.log(result);
});

Transaction

Use the api session.runInTransaction in order to run a unit of work in a managed transaction (begin/commit/retry)

session.runInTransaction((tx)=>{
	return tx.command("insert into V set name = :name", {params: { name: "test" }}).all()
}).then(({result,tx}) => {
	console.log(result);
	console.log(tx);
});

Live Queries

session.liveQuery("select from V").on("data", data => {
	console.log(data);
});

Running Tests

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

npm install

Then run the tests:

npm test

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.

Building from the Source Code

When building from source code, you need to download the driver directly from GitHub, then run NPM against the branch you want to use or test.

  1. Using Git, clone the package repository, then enter the new directory:

    $ git clone https://github.com/orientechnologies/orientjs.git
    $ cd orientjs
    
  2. When you clone the repository, Git automatically provides you with the current state of the master branch. If you would like to work with another branch, like develop or test features on past releases, you need to check out the branch you want. For instance,

    $ git checkout develop
    
  3. Once you've selected the branch you want to build, call NPM to handle the installation.

    $ npm install
    
  4. Run the tests to make sure it works:

    $ npm test
    

Changes

See CHANGELOG

License

Apache 2.0 License, see LICENSE

orientjs's People

Contributors

aeonrush avatar apliasun avatar bbtx0 avatar cpixl avatar danieljmaxwell avatar dehbmarques avatar dmarcelino avatar ffissore avatar gabipetrovay avatar hadson19 avatar ionicabizau avatar jpstrikesback avatar kelvin-ng avatar leeingnyo avatar luigidellaquila avatar lvca avatar mamobyz avatar matanshukry avatar nitrog7 avatar nitrogenlabs avatar orangemug avatar phpnode avatar rschmukler avatar saeedtabrizi avatar samsonradu avatar seeden avatar tglman avatar volune avatar welcomattic avatar wolf4ood avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

orientjs's Issues

sql order parse issue.

From @martingg88 on May 26, 2015 8:47

SELECT EXPAND(rid) FROM (SELECT story.release_date AS release_date, @Rid FROM resource ORDER BY (release_date DESC, ctime DESC) LIMIT 15)

can we remove the bracket for order clause because it will have sql parse issue if we include more than one field in order bracket.

(release_date DESC, ctime DESC)

Copied from original issue: codemix/oriento#319

Issue with multiple fields for OrderBy-clause in query builder

From @mamobyz on March 26, 2015 9:54

The statement.order() is supposed to work with

  • a string argument, e.g. order('age desc')
  • multiple string arguments, e.g. order('age asc', 'salary desc')
  • an array of strings, e.g order(['age asc', 'salary desc'])
  • an object with keys for the fields to be ordered by, and 'ASC' or 'DESC' as values
    is this correct?

When using the 2nd and third variant, if some of strings contain whitespaces, the resulted orderBy-clause is wrongly parenthesized, such that

ORDER BY (age asc), (salary desc)

which OrientDB then does not cope with.
Besides, I doubt that parentheses are rquired at all!
You can easily comprehend the issue in statement-test.js with the following test:

it('orders multiple fields', function() {
  this.statement.select().from('XYZ').order('field1 desc', 'field2');
  this.statement.toString().should.equal('SELECT * FROM XYZ ORDER BY field1 desc, field2');
});

Copied from original issue: codemix/oriento#291

Param is not working with embedded type [1.7.10]

From @dmarcelino on February 16, 2015 18:22

Hi @phpnode,

It seems 1654040 has caused a regression for saving embedded type on OrientDB v1.7.10 (not an issue on v2.0.2).

The error is:

OrientDB.RequestError: Error on execution of command: sql.INSERT INTO TestEmbedded SET name = "abc", obj = {"k1":"v1","k2":"v2"}

Copied from original issue: codemix/oriento#260

Is there a way to run an osql script when database is not created yet?

From @codeniac on March 4, 2015 16:21

I created a osql script that create my database and all classes/properties that are required! Now i'm wondering if there is a way to run this script only when the database is no present yet! And by "run the script" i mean a synchronous way to do it (i just step forward when the database is created).

Copied from original issue: codemix/oriento#280

corrupted.

From @martingg88 on May 19, 2015 10:34

any idea for following issue?

OrientDB.ProtocolError: Unknown Error on operation id REQUEST_COMMAND at Connection.process (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\transport\binary\connection.js:384:15) at Connection.handleSocketData (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\transport\binary\connection.js:279:17) at Socket.emit (events.js:107:17) at readableAddChunk (_stream_readable.js:163:16) at Socket.Readable.push (_stream_readable.js:126:10) at TCP.onread (net.js:529:20) From previous event: at Connection._sendOp (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\transport\binary\connection.js:79:10) at Connection.send (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\transport\binary\connection.js:63:17) at C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\transport\binary\connection-pool.js:65:23 From previous event: at ConnectionPool.send (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\transport\binary\connection-pool.js:64:4) at BinaryTransport.send (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\transport\binary\index.js:191:43) at Server.send (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\server\index.js:112:25) at Db.<anonymous> (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\db\index.js:152:24) at bound (domain.js:254:14) at Promise.runBound (domain.js:267:12) From previous event: at Db.send (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\db\index.js:144:4) at Db.exec (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\db\index.js:256:22) at Db.query (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\db\index.js:288:15) at module.exports.Statement.extend.exec (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\db\query.js:108:20) at module.exports.Statement.extend.one (C:\project\ctx\lib\node_modules\sails-orientdb\node_modules\oriento\lib\db\query.js:57:17) at C:\project\app\stream\api\services\oriento.js:374:26 at module.exports.dbHelper.getDB (C:\project\ctx\lib\node_modules\sails-orientdb\lib\connection.js:263:15) at bound.module.exports.adapter.getDB (C:\project\ctx\lib\node_modules\sails-orientdb\lib\adapter.js:195:44) at bound.self.(anonymous function) (C:\project\ctx\lib\node_modules\sails\node_modules\waterline\lib\waterline\query\adapters.js:35:29) at bound (C:\project\ctx\lib\node_modules\sails\node_modules\lodash\dist\lodash.js:729:21) at async.waterfall.action (C:\project\app\stream\api\services\oriento.js:368:23) at fn (C:\project\ctx\lib\node_modules\sails\node_modules\async\lib\async.js:641:34) at Immediate._onImmediate (C:\project\ctx\lib\node_modules\sails\node_modules\async\lib\async.js:557:34) at processImmediate [as _immediateCallback] (timers.js:358:17)

Copied from original issue: codemix/oriento#313

Build a query optimizer

Whaa, i miss the depreciation of oriento and the creation of this ! Nice work !

Context

Facebook just published a new way to express query from client to server and generally to build better app. This mark the end off rest endpoints (multiple round up ect).
But actually, if Graphql sends multiple database requests with fragments query), it wont be any benefit compared to rest in term of performance.

References

This issue may be solved by graphql team (see graphql/graphql-js#26) but it appears that having a way to let multiple queries be formulated than optimized before sending it to database (for instance when pressing queries.run() or smthg like this) may be a really benefit !!

http://rethinkdb.com/blog/lambda-functions/ may be an usefull article to read but i think that ORM and databases libraries like SQLAlchemy also implement such optimisation.

WDYT ?? Dis you also though such a system as a plus value ? Have it a place in orientjs or it would belong to the core ?

Maximum call stack size exceeded

db.select().from('Foo').all().then or .map ends with maximum call stack error. Vertex 'Foo' is 143.000 records. With .limit(121398 +/-) working fine. How can I avoid this limit?

embedded Date result in _NOT_PARSED_

From @rmemoria on May 29, 2015 16:45

I'm using the latest Oriento by now -> version 1.1.3.

I'm trying to insert the doc with an embedded doc using the declaration below:

db.insert().into('Person').set({
   inf:{
     utime:new Date()
   }
}).one().then(function(user) { console.log(user); })

but utime is not parsed as a date type.

When I check it in OrientoDB studio I get:

{
    "result": [
        {
            "@type": "d",
            "@rid": "#13:3",
            "@version": 1,
            "@class": "Person",
            "inf": {
                "udate": "_NOT_PARSED_"
            }
        }
    ],
    "notification": "Query executed in 0.027 sec. Returned 1 record(s)"
}

Is this a bug in oriento? Or the error is mine?

Thanks,
Ricardo

Copied from original issue: codemix/oriento#321

No drop database

If driver allow to create database by server.create, then it should allow to drop it same way like server.drop.

stringify-ing a traverse() result

From @Ovidiu-S on March 11, 2015 19:36

When trying to use the data returned by a TRAVERSE query, the result cannot be stringify'ed, because it has a circular structure.
I would rather not go trough the entire result set and remove all circular references.

waterline-orientdb uses
.removeCircularReferences (object)

Can this be accomplished with oriento ?

Copied from original issue: codemix/oriento#284

Connection is not reset if query is pending.

From @masimakopoulos on April 20, 2015 12:34

Hello and thanks for the great driver.

I came upon the following behaviour. I initialize a connection to the server globally using server.use(). I then execute multiple queries. If I stop and start OrientDB and I try to execute a query everything works as described in Issue #195 test. If I execute a query while the server is down though, the connection never recovers and I need to call server.use again to re-initialize the connection.

Maybe I overlooked something (maybe listening for an event or sth) but couldn't find anything related other than #195 in the docs/examples/tests

Copied from original issue: codemix/oriento#303

remove field.

From @martingg88 on February 27, 2015 10:37

remove method will work for following query?

update user remove birthday where @Rid = #23:14

Copied from original issue: codemix/oriento#271

server.use error catch?

From @odiel on March 10, 2015 3:22

Hi everyone

I have been trying to find a code sample or some guide to catch possible errors when executing

server.use('mydb');

bu I have not found anything. I can clearly see in the OrientDB logs the error related to the wrong credentials, but I would like to handle this scenario from the application point of view.

Thanks.

Copied from original issue: codemix/oriento#283

How to save large binary data using oriento on orientdb?

From @vjsrinath on May 26, 2015 1:16

I am trying to save image and video files directly in orientdb. After doing little bit of search, I saw the following documentation Binary Data. How to save bytes data using ORecordBytes with oriento.

Any help is appreciated. Thanks in advance.

Copied from original issue: codemix/oriento#316

How can I store binary data with ORecordBytes?

I am going to store some binary data using this method: https://orientdb.com/docs/last/Binary-Data.html#store-it-with-orecordbytes . I have tried something like that (with reference to ORecordBytes record = new ORecordBytes("Binary data".getBytes());):

db.class.get('V').then(function(V) {
    V.create(binary_data);
});

console.log(JSON.stringify(binary_data)) shows {"type":"Buffer","data":[8,0,18,16,8,0,16,0,24,1,34,3,97,98,99,42,3,100,101,102]}, i.e. a Buffer in Node.js. However, it does not work.

The data is actually a protobuf message sent through a WebSocket.

db.record.delete("#1:1") makes dirty links.

From @SangWoo-Maeng on May 29, 2015 12:48

OrientDB 2.0.7

In graph mode DB,
delete edge by rid like this.

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

The edge looks deleted but makes dirty links.
After execute that, in db console, repair database shows fixing links and docuements.

orientdb {db=test}> repair database
Repairing database...

  • Fixing dirty links...Done! Fixed links: 2, modified documents: 2
    Repair database complete (0 errors)

Dirty links, docs should not be made.

Please check it.

Copied from original issue: codemix/oriento#320

Using LET in raw query fails. What can I do?

From @SangWoo-Maeng on May 14, 2015 4:55

I want to query like this using LET and UNIONALL

SELECT EXPAND( $c ) LET
$a = ( SELECT expand(outE()) FROM #12:54),
$b = ( SELECT expand(out()) FROM #12:54 ),
$c = UNIONALL( $a, $b )

So, I tried query() and exec() in NodeJS

db.query( 'SELECT EXPAND( $c ) LET ' +
'$a = ( SELECT expand(outE()) FROM #12:54), ' +
'$b = ( SELECT expand(out()) FROM #12:54 ), ' +
'$c = UNIONALL( $a, $b )' )
.then(function(results) {
callback(results);
});

But it shows following error message in NodeJS

What can I do?

Unhandled rejection OrientDB.RequestError: Error on parsing query
Query: undefined
------^
at Operation.parseError (/home/ec2-user/lincall-server/node_modules/oriento/lib/transport/binary/protocol28/operation.js:832:13)
at Operation.consume (/home/ec2-user/lincall-server/node_modules/oriento/lib/transport/binary/protocol28/operation.js:422:35)
at Connection.process (/home/ec2-user/lincall-server/node_modules/oriento/lib/transport/binary/connection.js:360:17)
at Connection.handleSocketData (/home/ec2-user/lincall-server/node_modules/oriento/lib/transport/binary/connection.js:279:17)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:529:20)

  • At same time, OrientDB server shows message

Sent run-time exception to the client /52.68.202.249:34154: com.orientechnologies.orient.core.exception.OQueryParsingException: Error on parsing query
Query: undefined
------^
com.orientechnologies.orient.core.exception.OQueryParsingException: Error on parsing query
Query: undefined
------^
at com.orientechnologies.orient.core.sql.filter.OSQLTarget.(OSQLTarget.java:76)
at com.orientechnologies.orient.core.sql.OSQLEngine.parseTarget(OSQLEngine.java:440)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.parse(OCommandExecutorSQLSelect.java:218)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.parse(OCommandExecutorSQLSelect.java:96)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:56)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:37)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.command(OAbstractPaginatedStorage.java:1176)
at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:63)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.command(ONetworkProtocolBinary.java:1178)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.executeRequest(ONetworkProtocolBinary.java:385)
at com.orientechnologies.orient.server.network.protocol.binary.OBinaryNetworkProtocolAbstract.execute(OBinaryNetworkProtocolAbstract.java:217)
at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:69)
Caused by: com.orientechnologies.orient.core.exception.OCommandExecutionException: Class 'UNDEFINED' was not found in current database
at com.orientechnologies.orient.core.sql.filter.OSQLTarget.extractTargets(OSQLTarget.java:262)
at com.orientechnologies.orient.core.sql.filter.OSQLTarget.(OSQLTarget.java:67)
... 11 more

Copied from original issue: codemix/oriento#312

Problem with date before the start of Gregorian Calendar

Hi,

I have a problem when inserting date before the start of the gregorian calendar (10-15-1582)

If i insert a date in OrientDb before 10-15-1582, the date returned on select does not match to the inserted.

If i insert a date in OrientDb after 10-15-1582, the date returned on select match to the inserted.

I have created a unit test if you want to see :

describe("Bug 330: Select date before gregorian calendar", function () {
    this.timeout(10 * 10000);
    var LIMIT = 5000;
    before(function () {
        return CREATE_TEST_DB(this, 'testdb_bug_330')
            .bind(this)
            .then(function () {
                return this.db.class.create('User', 'V');
            })
            .then(function (item) {
                this.class = item;
                return item.property.create([
                    {
                        name: 'firstname',
                        type: 'String'
                    },
                    {
                        name: 'birthDate',
                        type: 'datetime'
                    }
                ])
            })
            .then(function () {
                return this.db.query('CREATE VERTEX User SET firstname = :firstname, birthDate = :birthDate',
                    {
                        params: {
                            firstname: 'Robert',
                            birthDate: new Date("1200-11-11T00:00:00.000Z")
                        }
                    }
                );
            })
            .then(function () {
                return this.db.query('CREATE VERTEX User SET firstname = :firstname, birthDate = :birthDate',
                    {
                        params: {
                            firstname: 'Marcel',
                            birthDate: new Date("1582-10-15T00:00:00.000Z") // Start Gregorian calendar
                        }
                    }
                );
            })
            .then(function () {
                return this.db.query('CREATE VERTEX User SET firstname = :firstname, birthDate = :birthDate',
                    {
                        params: {
                            firstname: 'Andrew',
                            birthDate: new Date("1987-03-03T00:00:00.000Z")
                        }
                    }
                );
            })
    });
    after(function () {
        return DELETE_TEST_DB('testdb_bug_330');
    });


    it('should get the previously inserted date', function () {

        return this.db.query('SELECT FROM User WHERE firstname = :firstname',
            {
                params: {
                    firstname: 'Robert'
                }
            }
        ).then(function (result) {

                var expectedDate = new Date("1200-11-11T00:00:00.000Z");
                result[0].birthDate.should.be.eql(expectedDate);

            })

    });

    it('should get the previously inserted date', function () {

        return this.db.query('SELECT FROM User WHERE firstname = :firstname',
            {
                params: {
                    firstname: 'Marcel'
                }
            }
        ).then(function (result) {

                var expectedDate = new Date("1582-10-15T00:00:00.000Z");
                result[0].birthDate.should.be.eql(expectedDate);

            })

    });

    it('should get the previously inserted date', function () {

        return this.db.query('SELECT FROM User WHERE firstname = :firstname',
            {
                params: {
                    firstname: 'Andrew'
                }
            }
        ).then(function (result) {

                var expectedDate = new Date("1987-03-03T00:00:00.000Z");
                result[0].birthDate.should.be.eql(expectedDate);

            })

    });
});

Transport layer timeout on query after a period of inactivity

From @osklyar on April 1, 2015 13:5

A query made with a once initialized and kept in that state DB object (var db = oriento({...}).use("somedb")) is running into a timeout at the transport socket level, [OrientDB.ConnectionError [2]: read ETIMEDOUT], first time I make a DB query after a longish period of inactivity between two DB access operations. A pause of 30min or so triggers the issue. Right after the timeout error the connection is somehow re-initialized and the next query runs fine. At the moment I solve the problem by scheduling a trivial select from ouser every minute, which is a fairly ugly workaround.

The expected behavior is for the driver to make sure the connection is alive and reestablish it when necessary without a long wait for the timeout and without timeout exceptions.

I might be missing some configuration option, and would be grateful for any hints what I should configure to reach the expected behavior.

See the original post at StackOverflow http://stackoverflow.com/questions/29257860/avoid-query-timeout-in-oriento-node-js-driver-for-orientdb

Copied from original issue: codemix/oriento#298

Ambiguous query format at .exec(query) or bug

OrientDB.RequestError: Cannot find a command executor for the command request: sql.begin

Environment

Component Deployed Instance
Machine Oracle VM VirtualBox, 2 x Intel Core i7-3517U 1.9 GHz, 2 GB RAM
OS Linux Mint 17.2 Mate 64-bit
OrientDB Community-2.1-rc5
NodeJs v.0.12.6
OrientJs v.2.0.0
OrientDB prtotocol plocal (28)

Steps to reproduce

1. Running code, including:

//...

//trying different query formats:
q='begin;create class Tmp1 extends V;create class Tmp2 extends V;commit retry 10;';
// or
q='begin\ncreate class Tmp1 extends V\ncreate class Tmp2 extends V\ncommit retry 10';

db.exec(q).then(function(r){

    //...

}).catch(function(e){

    //...

});

2. Getting result, including:

OrientDB.RequestError: Cannot find a command executor for the command request: sql.begin
create class Tmp1 extends V
create class Tmp2 extends V
commit retry 10
    at Operation.parseError (/web/dmn/esf4.loc/node_modules/uto/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:879:13)
    at Operation.consume (/web/dmn/esf4.loc/node_modules/uto/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:469:35)
    at Connection.process (/web/dmn/esf4.loc/node_modules/uto/node_modules/orientjs/lib/transport/binary/connection.js:380:17)
    at Connection.handleSocketData (/web/dmn/esf4.loc/node_modules/uto/node_modules/orientjs/lib/transport/binary/connection.js:281:17)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:538:20)

Question on vertex creation

From @kirankuppa on June 1, 2015 5:51

In my database, I consumer is a vertex and I am adding a new consumer record. I can accomplish this using the sql

  1. create class consumer extends V
  2. create vertex consumer set name="A1", user_id=1

I am trying to accomplish the same using oriento API. The docs give an example:

db.create('VERTEX', 'V')
.set({
  key: 'value',
  foo: 'bar'
})
.one()
.then(function (vertex) {
  console.log('created vertex', vertex);
});

Question 1 : Is this attempting to both create class (with name 'VERTEX' and extending 'V') as well as creating a record with keys ('key', 'foo')?

If so, having created the schema before hand which includes creating the vertex 'consumer', can I do the following to create a new record for consumer

db.create('consumer')
.set({
  name: 'A1',
  user_id: 1
})
.one()
.then(function (vertex) {
  console.log('created vertex', vertex);
});

Copied from original issue: codemix/oriento#322

Deadlock when multiple connections make simultaneous requests

NOTE I'm not sure if this is a bug in OrientDB or if it has anything to do with OrientJS so I've created this issue in both repositories. Please see orientechnologies/orientdb#4625 for the OrientDB issue

We are running OrientDB 2.1-rc4 (this has also attempted with 2.1-rc5) as a distributed database and our driver is NodeJS pacakge orientjs (latest version from npm OR from github at commit 5b0035aec7fdcab75ff0e1492117ad7d881dd434).

If more than one connection attempts to query the database at once, the database appears to become deadlocked. No responses are sent to the clients and furthermore we must stop and terminate the server process manually - in other words, the java process becomes unresponsive and doesn't shut down when it receives SIGTERM.

We are running the server process on OSX (and we've tried this on linux as well) with Java 8 and are using the following distributed-db-config.json:

{
  "autoDeploy": true,
  "hotAlignment": false,
  "executionMode": "undefined",
  "readQuorum": 1,
  "writeQuorum": 1,
  "failureAvailableNodesLessQuorum": false,
  "readYourWrites": true,
  "servers": {
    "*": "master"
  },
  "clusters": {
    "internal": {
    },
    "index": {
    },
    "*": {
      "servers": ["<NEW_NODE>"]
    }
  }
}

We've noticed that if the connections do NOT query the database simultaneously, then there is no problem. The deadlock only appears to occur if more than one client issues a request to the database at the same time. We've also noted that this problem appears to have been introduced in 2.1-rc4, it did not exist in 2.1-rc3.

Here is an example script which you can use to reproduce the issue yourself:

#!/usr/bin/env node
'use strict';

var orientjs = require('orientjs');
var Promise = require('bluebird');

// NOTE this works successfully only if the connection count is 1.
var CONNECTION_COUNT = 2;

class Connection {
    constructor() {
        // NOTE change these settings to match your own.
        this.server = orientjs({
            host: 'localhost',
            port: 2424,
            username: 'root',
            password: 'password'
        });

        // NOTE change these settings to match your own.
        this.db = this.server.use({
            name: 'GratefulDeadConcerts',
            username: 'admin',
            password: 'admin'
        });
    }
}

var connections = [];
var promises = [];

// Create some number of connections...
for(var i = 0; i < CONNECTION_COUNT; i++) {
    connections.push(new Connection());
    console.info(`Created connection: ${i}`);
}

// For each connection, query the number of vertices in the database.
// Collect the Promises as we go...
connections.forEach(function(connection) {
    promises.push(
        connection.db.select('count(*)').from('V').scalar()
        // NOTE if CONNECTION_COUNT > 1, none of the following happens:
        .then(function(count) {
            console.info(`count: ${count}`);
        })
        .catch(function(err) {
            console.error(err);
        })
    );
});

// Wait for all Promises to resolve and exit.
Promise.all(promises)
.finally(function(err) {
    // NOTE this never happens!
    console.info('All OK!');
    process.exit(0);
});

Gremlin API

From @danieljoppi on May 12, 2015 17:40

Are there any plans to add Gremlin-compliant syntax fluent API?

Copied from original issue: codemix/oriento#311

suggestion to add .save and .delete method on record object

Hi,

I was wondering to extend record object to include .save() and .delete() method.

eg

db.select().from('OUser').where({status: 'ACTIVE'}).one()
.then(function (user) {
   user.status = 'deactivated';
   return user.save();
});

what do you think?

Insert.into clause should work with string with whitespaces

From @mamobyz on May 26, 2015 8:15

With reference to orientechnologies/orientdb#3406, as it is suggested there to use syntax like insert into <class_name> cluster <cluster_name> set ... to specify a particular cluster to be inserted into.

Oriento on the other hand always parenthesizes a string with whitespaces, such as insert into (<class_name> cluster <cluster_name>) set ... which OrientDB does not accept as a valid statement.

I think, there are many places where Oriento inappropriately apply util.requiresParens(). Other examples are #291, #292.

Copied from original issue: codemix/oriento#317

livequery api does not normelize rid

when a result is retured from a live query api update call it looks like this:
{ content: { '@type': 'd', '@Class': 'players', name: 'Maxwell', score: 120 }, type: 'd', cluster: 12, position: 41, version: 0 } }

then the using application needs to combine cluster and postion to get the rid as described here:
http://orientdb.com/docs/2.0/orientdb.wiki/Tutorial-Record-ID.html

this seems like an uncositstent api issue since objects returned from '*' selects do have @Rid as a field

expand is not working without a fetchplan

From @orangemug on March 2, 2015 17:5

Oriento needs fetch along with expand to function correctly, for example the following in orientdb studio works as expected and returns the full expanded object

select expand(item) from #1:3

The oriento version does not

db.select("expand(item)").from(someRID)

Here are some commits that show the problem

Copied from original issue: codemix/oriento#275

OrientJS fails silently when no credential is supplied for database

I had a database with no roles attached to any of OUsers in its Schema and I tried to connect just by using server.use('dbname') and then apply a simple query to it, such as db.select().from('OUser'). Any of the Promises functions fullfill, reject or catch were called. Is this the expected behavior? I was expecting something like a SecurityException or Authentication Error.

Fully support the REST API

From @phpnode on April 30, 2014 21:24

The beginnings of REST support were added in #31 but it's a long way from being usable. It's important that we implement a consistent API for both REST and binary transports, but unfortunately the results of REST calls for certain operations do not map 1 - 1 with the same operations in the binary protocol.

Things to do (in order):

  • Implement a process() method in the REST and binary protocol operations which smooths over the differences between the two.
  • Implement the remaining REST operations
  • Documentation
  • Try browserifying it

Copied from original issue: codemix/oriento#44

how to close a db instance?

From @majordo on March 2, 2015 17:36

Hello,
I'm using v. 1.1.3.
I'm trying to close the db instance I'm working with, but no way.

This is what I'm doing:

var Oriento = require('oriento');
oriento = Oriento(config);
db = oriento.use('test');
db.select().from('OUser').all().then(console.log.bind(console));
db.close().then("ok!");

But nothing happens.

Any suggestions?

Thanks in advance
Luca

Copied from original issue: codemix/oriento#276

Using tokens instead off username/pwd authentication

From @blue-coder on March 5, 2015 10:11

How is it possible to apply a stateless server communication using tokens, example in such use case:

A state-full connection established with server for first time using 'use' method so token buffer could be found in database object.
Subsequent calls to server should use token instead of asking user to supply username and password for every query

Is that possible? how?

Copied from original issue: codemix/oriento#281

livequery process, keeps throwing errors when the live result is not the first in the processing queue

In cases when the processing queue contains LIVE_RESULT only on the second or third member it throws an
Unhandled rejection OrientDB.ProtocolError:
Unsupported operation status: 6
while 6 is the LIVE_RESULT operation status and should be fully supported
this mostly happens when quite a few updates are very quickly emited

Connection.prototype.process = function (buffer, offset) {
  var code, parsed, result, status, item, op, deferred, err, token, operation;
  offset = offset || 0;
  if(this.queue.length === 0){
    op = new Operation();//TODO refactor this!
    parsed = op.consume(buffer, offset);
    status = parsed[0];
    if (status === OperationStatus.PUSH_DATA) {
      offset = parsed[1];
      result = parsed[2];
      this.emit('update-config', result);
      return offset;
    }else if(status === OperationStatus.LIVE_RESULT){
      token = parsed[1];
      operation = parsed[2];
      result = parsed[3];
      offset = parsed[4];
      this.emit('live-query-result', token, operation, result);
      return offset;
    }
  }
  while ((item = this.queue.shift())) {
    op = item[0];
    deferred = item[1];
    parsed = op.consume(buffer, offset);
    status = parsed[0];
    offset = parsed[1];
    result = parsed[2];
    if (status === OperationStatus.READING) {
      // operation is incomplete, buffer does not contain enough data
      this.queue.unshift(item);
      return offset;
    }
    else if (status === OperationStatus.PUSH_DATA) {
      this.emit('update-config', result);
      this.queue.unshift(item);
      return offset;
    }
    else if (status === OperationStatus.COMPLETE) {
      deferred.resolve(result);
    }
    else if (status === OperationStatus.ERROR) {
      if (result.status.error) {
        // this is likely a recoverable error
        deferred.reject(result.status.error);
      }
      else {
        // cannot recover, reject everything and let the application decide what to do
        err = new errors.Protocol('Unknown Error on operation id ' + op.id, result);
        deferred.reject(err);
        this.cancel(err);
        this.emit('error', err);
      }
    }
    else {
      deferred.reject(new errors.Protocol('Unsupported operation status: ' + status));
    }
  }
  return offset;
};

Comma-separators missing in OrderBy-clause

From @mamobyz on March 26, 2015 9:59

With reference to issue #291, if an object argument with multiple attributes is passed on to statement.order(), the resulted orderBy-clause does not contain commas.

it('orders multiple fields', function(){
  this.statement.select().from('XYZ').order({field1:'', field2:'desc'});
  this.statement.toString().should.equal('SELECT * FROM XYZ ORDER BY field1, field2 desc');
});

Am I mistaking something?

Copied from original issue: codemix/oriento#292

Feature request: use access_token from HTTP api in query statements

Since OrientDB has graph partitioning built in for multi-tenancy apps, it would be a huge benefit to allow an application client to retain only a single connection to an OrientDB instance -- and allow the application to handle passing around the user's access token.

I imagine the workflow as such:

1. User authenticates via issuing a post request to /token/DB_NAME:

curl --data "grant_type=password&username=admin&password=admin" http://localhost:2480/token/foobar

The response looks something like this:

{
"@type": "d",
"@version": 0,
"access_token": "eyJAdHlwZSI6ImQiLCJAdmVyc2lvbiI6MCwidHlwIjoiT3JpZW50REIiLCJhbGciOiJIUzI1NiIsImtpZCI6IiJ9.eyJAdHlwZSI6ImQiLCJAdmVyc2lvbiI6MCwiaXNzIjpudWxsLCJleHAiOjE0Mzc0NDM1Nzk1OTQsImlhdCI6MTQzNzQzOTk3OTU5NCwibmJmIjoxNDM3NDM5OTc5NTk0LCJzdWIiOiJ3c3giLCJhdWQiOiJPcmllbnREQiIsImp0aSI6Ijg4Y2NiZjVkLTQ3YzktNDJhYS1hMWIzLWI5ODBmZTY4ZDkwZSIsInVpZGMiOjUsInVpZHAiOjAsImJkdHlwIjpudWxsLCJAZmllbGRUeXBlcyI6ImV4cD1sLGlhdD1sLG5iZj1sLHVpZHA9bCJ9.4Ypb81ultpLgxK0A-JsgIjhcSanTWjyz5iw7LHY63r0=",
"expires_in": 3600
}

2. Client application retains the value of access_token from the response and uses it for every query related to a partitioned dataset.

db.select().token(access_token).from('Some_Collection')

If this is already possible, then it would be greatly appreciated to provide an example and documentation around it.

I know there is the db.createUserContext method which takes a token, but even if I create a buffer from the value of access_token in the HTTP response, it doesn't work.

This is an absolutely critical feature for any large scale app that needs data partitioning -- in my case, separate database connections for each user will not be a realistic option when there are 5,000 to 10,000 users connected at the same time.

3. Make this work with live queries.

This would allow for OrientDB to be significantly easier to integrate into real-time projects like Meteor.

unsupported pushed data format

From @nin-jin on March 27, 2015 9:40

server.create({
    name: name,
    type: 'document',
    storage: 'plocal'
}) )

error in console:

unsupported pushed data format: LlocalName:"_hzInstance_1_orientdb",localId:"5d5c25e9-f212-4c2f-ac28-3ce38852ecf7",members:[(id:"5d5c25e9-f212-4c2f-ac28-3ce38852ecf7",name:"alpha",startedOn:1427448886248t,listeners:[{"protocol":"ONetworkProtocolBinary","listen":"192.168.59.3:2424"},{"protocol":"ONetworkProtocolHttpDb","listen":"192.168.59.3:2480"}],databases:<>)]

OrientDB: 2.0.5

Copied from original issue: codemix/oriento#295

EXPORT DATABASE doesn't support multi-inheritance

I've recently tried to use the EXPORT DATABASE command to set up a fixture schema to quickly set up and tear down a testing database. In my database, I make use of multi-inheritance, however it seems that the JSON format used only has a single field for the SuperClass, not an array field. This means only the first superclass is saved, and subsequently imported.

Param double use bug

From @dvine-multimedia on March 17, 2015 21:18

Hi.

I have another weird one :)
Double use of a single parameter doesn't work. The weirdest thing: toString() shows the correct query.

This query doesn't work. The recipient = :id clause isn't set.

DB
  .select()
  .from('Message')
  .where('(sender = :id or recipient = :id)')
  .addParam('id', userId)

The .toString() correctly shows
SELECT * FROM Message WHERE (sender = #13:2 or recipient = #13:2)
though.

If you make two different parameters, it does work.

DB
  .select()
  .from('Message')
  .where('(sender = :id1 or recipient = :id2)')
  .addParam('id1', userId)
  .addParam('id2', userId)

Cheers
Georg

Copied from original issue: codemix/oriento#288

adding .where() to delete changes command to select

Hi,

had an occasion to delete an edge based on a condition and sent this command:
db.delete("EDGE","Token").where("13:2 in out.@Rid")
to achieve following command:
Delete Edge Token where 13:2 in out.@Rid.
it did not work and when i have looked at shell running orient db I have seen this:
select Edge Token where 13:2 in out.@Rid.

seems adding .where to chain turns the initial statement to select.

invalid data return for Embeddedmap

From @martingg88 on May 21, 2015 13:59

I do have found no class or class is empty due to the following flow. Does your library modify embeddedmap data before return to client?

  1. First, i have stored the data as follows;

{ credit: { crew: [],actor: [] }},

  1. Second, when i query from database and it return me the result which have add the '@type', 'type' and '@Class' into the data? any idea.
    { credit: { '@type' : '', @Class: '', type: 'document', crew: [],actor: [] }},
  2. i will have the issue if i save the data that is returned from the previous query because the @Class is null/empty. I think @Class shouldn't be involved into this json data.

Copied from original issue: codemix/oriento#315

Adding multiple properties to a class

Rather than executing multiple queries to add multiple properties to a class, is there a way which can add properties to a class from a single query?

MyClass.property.create({
  name: 'name',
  type: 'String'
})

Unhandled rejection OrientDB.RequestError: Server user not authenticated.

From @martingg88 on April 25, 2015 6:9

I do have following and it only happen when i edit and save my node.js code. any idea?

Unhandled rejection OrientDB.RequestError: Server user not authenticated.
at Operation.parseError (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\transport\b
inary\protocol28\operation.js:832:13)
at Operation.consume (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\transport\bina
ry\protocol28\operation.js:422:35)
at Connection.process (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\transport\bin
ary\connection.js:360:17)
at Connection.handleSocketData (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\tran
sport\binary\connection.js:279:17)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:529:20)
From previous event:
at Connection._sendOp (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\transport\bin
ary\connection.js:79:10)
at Connection.send (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\transport\binary
\connection.js:63:17)
at C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\transport\binary\connection-pool.
js:65:23
at processImmediate as _immediateCallback
From previous event:
at ConnectionPool.send (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\transport\bi
nary\connection-pool.js:64:4)
at BinaryTransport.send (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\transport\b
inary\index.js:191:43)
at Server.send (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\server\index.js:112:
25)
at Server.list (C:\project\app\sport\node_modules\sails-orientdb\node_modules\oriento\lib\server\index.js:248:
15)
at module.exports.ensureDB (C:\project\app\sport\node_modules\sails-orientdb\lib\connection.js:26:20)
at module.exports.getDb (C:\project\app\sport\node_modules\sails-orientdb\lib\connection.js:49:20)
at module.exports.connect (C:\project\app\sport\node_modules\sails-orientdb\lib\connection.js:426:13)
at Object.module.exports.create (C:\project\app\sport\node_modules\sails-orientdb\lib\connection.js:451:20)
at module.exports.getConn (C:\project\app\sport\node_modules\sails-orientdb\lib\adapter.js:50:23)
at Object.module.exports.adapter.registerConnection (C:\project\app\sport\node_modules\sails-orientdb\lib\adap
ter.js:111:13)
at C:\project\app\sport\node_modules\sails\node_modules\waterline\lib\waterline.js:203:29
at C:\project\app\sport\node_modules\sails\node_modules\async\lib\async.js:125:13
at Array.forEach (native)
at _each (C:\project\app\sport\node_modules\sails\node_modules\async\lib\async.js:46:24)
at Object.async.each (C:\project\app\sport\node_modules\sails\node_modules\async\lib\async.js:124:9)
at Array.async.auto.registerConnections (C:\project\app\sport\node_modules\sails\node_modules\waterline\lib\wa
terline.js:176:13)
at C:\project\app\sport\node_modules\sails\node_modules\async\lib\async.js:487:38
at Array.forEach (native)
at _each (C:\project\app\sport\node_modules\sails\node_modules\async\lib\async.js:46:24)
at Object.async.auto (C:\project\app\sport\node_modules\sails\node_modules\async\lib\async.js:458:9)
at Waterline.initialize (C:\project\app\sport\node_modules\sails\node_modules\waterline\lib\waterline.js:121:9
)
at buildORM (C:\project\app\sport\node_modules\sails\lib\hooks\orm\build-orm.js:52:15)
at Array.async.auto.instantiatedCollections (C:\project\app\sport\node_modules\sails\lib\hooks\orm\index.js:20
3:11)
at listener (C:\project\app\sport\node_modules\sails\node_modules\async\lib\async.js:493:46)
at C:\project\app\sport\node_modules\sails\node_modules\async\lib\async.js:444:17

Copied from original issue: codemix/oriento#307

Invalid querybuilder transformation for arrays of RIDs

db.select('count(*)').from([rid1,rid2]).where({"@class": "Entity"})
builds an invalid query. The two RIDs are joined with ,, resulting in SELECT FROM #14:1, #14:2, which is invalid. They should be surrounded with square brackets, like SELECT FROM [#14:1, #14:2].

Furthermore, my initial workaround of
db.select('count(*)').from([${rid1}, ${rid2}]).where({"@class": "Entity"})
also did not work, I realised this was due to the space in between the RIDs which caused the whole expression to be parenthesised.

Workaround that worked for me:
db.select('count(*)').from([${rid1},${rid2}]).where({"@class": "Entity"})

newtork pools management issue.

I found out that network pool set to greater than 1 will most likely to cause some issue (e.g. transaction rollback, freeze update and ...)

Here is the test script to prove one of the mentioned issue above (etc. transaction rollback).
You may need to set "config.pool.max" to 1 or 2 or even more to see the issue.
You may need to set "config.username" and "config.password" to your own one.
we have some more discussion on this link.

https://github.com/codemix/oriento/issues/331#event-333570751

var path = require('path');
var Bluebird = require('bluebird');

var oriento_lib_root = path.resolve(__dirname, '../../', 'lib');
var oriento_lib = require(oriento_lib_root);

var config = {
"host": "localhost",
"port": "2424",
"pool": {
"max": 2
},
"transport": "binary",
"username": "root",
"password": "",
"database":{
"name": "testdb"
}
}

var TEST_SERVER = new oriento_lib.Server({
host: config.host,
port: config.port,
username: config.username,
password: config.password,
transport: config.transport,
pool: config.pool,
useToken: true
});

var record = {
'name' : 'demo',
'metadata' : {"genre":[],"budget":0,"translation":{"@type":"d","@Version":0,"title":[]},"vote_average":0,"type":"trailer","production":{"@type":"d","@Version":0,"company":[],"country":[]},"country":[{"name":null,"code":"US","date":""}],"title":"In Stereo","overview":"David and Brenda are perfect for each other, and everyone knows it except David and Brenda. After a break-up, they each experience their own rough patch. For David, a self-destructive artistic endeavor and a relationship with an immature beauty—for Brenda, a failing acting career, an eviction notice, and a boyfriend who just doesn’t do it for her. A chance encounter brings them together on the streets of New York at a particularly bad time. David invites Brenda to the opening of his first photography exhibit and the stage is set for a night of drinking and flirting which leads to an untraditional proposal of how they can be together without getting back together. A sharply observed, un-romantic comedy by writer/director Mel Rodriguez III, IN STEREO is a stylish and striking first feature that offers an unflinching look at the complexity of modern relationships.","source":{"@type":"d","@Version":0,"imdb":"tt3478186","themoviedb":340189},"poster":"http://image.tmdb.org/t/p/original/QfnnGjCpvtJ0aY6IWKKnog2viF.jpg","release_date":"2015-07-03","language":"en","vote_count":0,"credit":{"@type":"d","@version":0,"crew":[],"actor":[]},"release":{"@type":"d","@version":0,"country":[{"name":null,"code":"US","date":"2015-07-03"}]},"popularity":0.159291,"revenue":0}
};

describe('Database API', function () {

before(function () {
this.timeout(0);

this.config = config;
this.collections = {};

this.db = '';
this.class = '';
this.rid = '';

return TEST_SERVER.create({
  name: this.config.database.name,
  type: 'graph',
  storage: 'plocal'
})
.bind(this)
.then(function(db) {
  this.db = db;
  return db.class.create('test', 'V');
})
.then(function (testClass) {
  this.class = testClass;
  return testClass.property.create([
    {
      name: 'name',
      type: 'String'
    },
    {
      name: 'metadata',
      type: 'EMBEDDEDMAP'
    }
  ]);
})
.then(function () {
  return Bluebird.all([
    this.db.index.create({
      name: 'test.name',
      class: 'test',
      properties: 'name',
      type: 'FULLTEXT ENGINE LUCENE'
    }),
    this.db.index.create({
      name: 'test.metadata',
      class: 'test',
      properties: 'metadata',
      type: 'FULLTEXT ENGINE LUCENE',
    })
  ]);
})
.then(function () {
  return this.db
    .insert()
    .into('test')
    .set(record)
    .transform({
      '@rid': function (rid) {
          return '#' + rid.cluster + ':' + rid.position;
      }
    })
    .one()
})
.then(function (result) {
  this.rid = result['@rid'];
});

});

after(function () {
this.timeout(0);
return TEST_SERVER.drop({
name: this.config.database.name,
storage: 'plocal'
});
});

describe('Db::update()', function () {
it('should have transaction rollback', function () {
this.timeout(0);
var parallel = [];
var max_try = 100;
for(i = 0; i < max_try; i++){
parallel.push(
this.db.let('test', function (s) {
s.insert().into('test').set(record);
})
.commit()
.return('$test')
.transform({
'@Rid': function (rid) {
return rid.toString();
}
})
.one()
);
}
return Bluebird.all(parallel);
});

});
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.