Baffled by all this Node -> Titan stuff - node.js

I'm new to Java, Gremlin, Nodejs, Tickerpop, Maven and just about everything else. What does this code do? In particular what is 'java.import' doing? Is it a Java class? What has this got to do with Titan?
var Titan = require('titan-node');
var gremlin = new Titan.Gremlin({ loglevel: 'OFF' });
var TinkerGraphFactory = gremlin.java.import('com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory');
var graph = TinkerGraphFactory.createTinkerGraphSync();
var g = gremlin.wrap(graph);
g.V('name', 'marko').next(function (err, v) {
v.getProperty('name', function (err, value) {
console.log(value);
});
});
Why when I use the Rexster can I not see the database being queried here?

To add to #mscdex valid answer.
This is JavaScript-flavored Gremlin code in Node.js using direct Java bindings via node-java.
Gremlin is not a language per se but a DSL. It is most of the time written in Groovy (because of its shortened syntax over Java), but it also exists in any JVM-compliant languages (ie. Java, Groovy, Scala, JavaScript via rhino and now nashorn with Java 8, to name a few). The full Groovy/Java API is accessible when typing Gremlin queries/scripts, which makes it a turing-complete "language".
I recommend reading http://gremlindocs.com/ and http://sql2gremlin.com for interesting beginner resources on Gremlin. http://www.tinkerpop.com/docs/3.0.0.M1/ will give you detailed information on TinkerPop and Gremlin (note: link will break as official v3.0 doc is released).
Because of the way node-java works and exposes Java methods (sync/async), you're required to use callbacks here in order to not block the event loop. This is a JavaScript concern and has nothing to do with Gremlin strictly speaking.
There a couple other clients which do not bind to the JVM directly but uses HTTP for TinkerPop 2.x (https://github.com/gulthor/grex for Node.js) or WebSocket for TinkerPop 3.0+ (https://github.com/gulthor/gremlin-client, for Node.JS/browsers, which will become the official TP3 JavaScript driver). Note: TinkerPop member / lib author here.

gremlin (a dependency of titan-node) uses node-java, which is a module that provides a bridge between node and Java. node-java allows you to import Java classes, instantiate Java data types, etc.
So what you're seeing is node-java importing a particular Java class because Gremlin is a Java/JVM thing.

Related

How do I verify the consistency level configured on the Java driver?

We are currently upgrading from 3.x to 4.x. We are using the programaticBuilder for the DriverConfigLoader. Below is the code for same.
DriverConfigLoader driverConfigLoader = DriverConfigLoader.programmaticBuilder()
.withDuration(DefaultDriverOption.HEARTBEAT_INTERVAL, Duration.ofSeconds(60))
.withString(DefaultDriverOption.REQUEST_CONSISTENCY, ConsistencyLevel.LOCAL_QUORUM.name())
.withString(DefaultDriverOption.RETRY_POLICY_CLASS, "DefaultRetryPolicy")
.withString(DefaultDriverOption.RECONNECTION_POLICY_CLASS, "ConstantReconnectionPolicy")
.withDuration(DefaultDriverOption.RECONNECTION_BASE_DELAY, Duration.ofSeconds(5))
.withString(DefaultDriverOption.LOAD_BALANCING_POLICY_CLASS, "DcInferringLoadBalancingPolicy")
.build();
Wanted to check how to verify this correct setting of ConsistencyLevel when the write/read happens. is there a debug log print mechanism available for this purpose.
Your question suggests that you don't trust that the configured consistency level is not being honoured by the driver so you're looking for proof that it does. To me it doesn't make sense. Perhaps you ran into another problem related to request consistency and you should post information about that instead.
In any case, the DriverConfigLoader is provided for convenience but we discourage its use because it means that you are hard-coding configuration within your app which is bad practice. If you need to make a change, you are forced to have to recompile your app again by virtue that the configuration is hardcoded. Only use the programmatic loader if you have a very specific reason.
The recommended method for configuring the driver options is to use an application configuration file (application.conf). The advantages include:
driver options is configured in a central location,
hot-reload support, and
changes do not require recompiling the app.
To set the basic request consistency to LOCAL_QUORUM:
datastax-java-driver {
basic {
request {
consistency = LOCAL_QUORUM
}
}
}
For details, see Configuring the Java driver. Cheers!
For DataStax Java Driver 4.x version you can do something like this:
CqlSession session = CqlSession.builder().withConfigLoader(driverConfigLoader).build();
DriverConfig config = session.getContext().getConfig();
config.getProfiles().forEach(
(name, profile) -> {
System.out.println("Profile: " + name);
profile.entrySet().forEach(System.out::println);
System.out.println();
});
This will print the values for every defined option in every defined profile. It won't print undefined options though.

Where can I find the url or ip address of SQL Server Database [duplicate]

Is there any way I can get my Node.js app to communicate with Microsoft SQL?
I haven't seen any MS SQL drivers out there in the wild?
I'm putting a very simple app together and need to be able to communicate with an existing MS SQL database (otherwise I would have gone with mongoDB or Redis)
The original question is old and now using node-mssql as answered by #Patrik Šimek that wraps Tedious as answered by #Tracker1 is the best way to go.
The Windows/Azure node-sqlserver driver as mentioned in the accepted answer requires you to install a crazy list of prerequisites: Visual C++ 2010, SQL Server Native Client 11.0, python 2.7.x and probably also Windows 7 SDK for 64-bit on your server. You don't want to install all these GB's of software on your Windows Server if you ask me.
You really want to use Tedious. But also use node-mssql to wrap it and make coding a lot easier.
Update August 2014
Both modules are still actively maintained. Issues are responded on quite quickly and efficiently.
Both modules support SQL Server 2000 - 2014
Streaming supported since node-mssql 1.0.1
Update February 2015 - 2.x (stable, npm)
Updated to latest Tedious 1.10
Promises
Pipe request to object stream
Detailed SQL errors
Transaction abort handling
Integrated type checks
CLI
Minor fixes
This is plain Tedious:
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var config = {
server: '192.168.1.212',
userName: 'test',
password: 'test'
};
var connection = new Connection(config);
connection.on('connect', function(err) {
executeStatement();
}
);
function executeStatement() {
request = new Request("select 42, 'hello world'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
connection.close();
});
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(column.value);
}
});
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
// In SQL Server 2000 you may need: connection.execSqlBatch(request);
connection.execSql(request);
}
Here comes node-mssql which has Tedious as a dependency. Use this!
var sql = require('mssql');
var config = {
server: '192.168.1.212',
user: 'test',
password: 'test'
};
sql.connect(config, function(err) {
var request = new sql.Request();
request.query("select 42, 'hello world'", function(err, recordset) {
console.log(recordset);
});
});
A couple of new node.js SQL server clients have just released recently. I wrote one called node-tds and there is another called tedious
We just released preview drivers for Node.JS for SQL Server connectivity. You can find them here:
http://blogs.msdn.com/b/sqlphp/archive/2012/06/08/introducing-the-microsoft-driver-for-node-js-for-sql-server.aspx
(duplicating my answer from another question).
I would recommend node-mssql, which is a nice wrapper for other connectors, the default being my previous choice (Tedious) bringing a bit nicer of an interface. This is a JavaScript implimentation, with no compilation requirements, meaning you can work in windows and non-windows environments alike.
Another option, if you don't mind bringing in .Net or Mono with a binary bridge would be to use edge.js. Which can be very nice if you want to leverage .Net libraries in node.js
node-tds is abandoned, node-odbc doesn't work with windows, and the MS node-sqlserver driver doesn't seem to work on non-windows (and has some goofy requirements).
There is another module you can use - node-mssql. It uses other TDS modules as drivers and offer easy to use unified interface. It also add extra features and bug fixes.
Extra features:
Unified interface for multiple MSSQL drivers
Connection pooling with Transactions and Prepared statements
Parametrized Stored Procedures for all drivers
Serialization of Geography and Geometry CLR types
Smart JS data type to SQL data type mapper
Support both Promises and standard callbacks
You could maybe use node-tds.js:
An exciting implementation of the TDS protocol for node.js to allow communication with sql server...
USAGE:
var mssql = require('./mssql');
var sqlserver = new mssql.mssql();
sqlserver.connect({'Server':__IP__,'Port':'1433','Database':'','User Id':'','Password':''});
var result = sqlserver.execute("SELECT * FROM wherever;");
TSQLFTW - T-SQL For The WIN(dows) - by Fosco Marotto
https://github.com/gfosco/tsqlftw
It is a C# and ADO .NET managed code solution, with a C++ wrapper that Node.js can import and work with.
If you know .NET you could try WCF Data Services (ADO.NET Data Services); write an WCF app for data access and use odata (REST on steroids) to interact with the database
WCF Data Services: http://msdn.microsoft.com/en-us/data/bb931106
OData: http://www.odata.org/
If you are into SOA and use SQL Server 2005 you could check out the Native XML Web Services for Microsoft SQL Server 2005
http://msdn.microsoft.com/en-us/library/ms345123(v=sql.90).aspx
You could access SQL Server as a web service (HTTP, SOAP)
Microsoft (The Windows Azure Team) just released a node driver for SQL SERVER.
It has no package for npm yert, as far as I know, but it is open sourced. And the accepting community contribution too.
https://github.com/WindowsAzure/node-sqlserver
Introduction blog post here:
http://blogs.msdn.com/b/sqlphp/archive/2012/06/08/introducing-the-microsoft-driver-for-node-js-for-sql-server.aspx
I'd suggest taking a look at Prisma. We just (October 2020) announced preview support for SQL Server.
Prisma is an ORM that puts the emphasis on type-safety and developer experience. Unlike traditional ORMs that typically map tables to classes, Prisma maps queries to types (in TypeScript) and returns plain objects from queries.
To get started with Prisma and SQL Server check out this example and start from scratch guide in the docs.
If you are running on .NET look at entityspaces.js at, we are creating an entire universal ORM for Node.js that will not require a WCF JSON service ... https://github.com/EntitySpaces/entityspaces.js
If you are using MSFT backend technology you could use it now, however, we are creating a universal Node.js ORM and will have more information on that soon
There is an update from Microsoft. Here is a series of blog posts (part 1 and part 2).
Node.js SQL Server drivers seem very immature - there's a mish-mash of different projects with varying dependencies, performance, and levels of completeness, none of which inspire confidence.
I'd propose using edge-sql. This leverages .NET's mature database driver ecosystem, and depends only on .NET (a no-brainer if you are running node on Windows - if not there is Mono, but I have not tried that).
Here is a node example (server.js) using edge-sql (note you need to put your connection string into an environment variable as per edge-sql docs):
var edge = require('edge');
// edge-sql has built in support for T-SQL / MSSQL Server
var getData = edge.func('sql', function () {/*
select top 10 * from sometable
*/
});
getData(null, function (error, result) {
if (error) throw error;
console.log(result);
});
You can also leverage Edge.js with .NET to access other databases, such as Oracle. I have given an example of that approach here.
The status as of May 2016 is as follows.
The official Microsoft SQL Driver for Node, called node-sqlserver, has not been updated for a number of years.
There is a new fork on this called node-sqlserver-v8 that works with Node Versions 0.12.x. and >= 4.1.x. This fork also has pre-compiled binaries for x64 and x86 targets.
The package is available on NPM as msnodesqlv8.
I recommend this package because it is lightweight (has no dependencies) and it is the only one that works with all recent version of SQL Server, including SQL LocalDB.
Now (2016) you can use Sequelize ORM that supports:
MySQL / MariaDB,
PostgreSQL
SQLite
Microsoft SQL Server
It is widely used according to its Github's stars.
that link details only a sql 2000 solution, not sql 2005 nor sql 2008, and also that code only allow sending sql text, and does not allow the execution of stored procedures.
The real solution would be to install node JS on a linux server, or on a virtual linux server on a windows machine, and then go to microsoft web site and download the JDBC java drivers and install those microsoft ms sql java jdbc drivers on either the linux server or linux virtual server.

How to set protocol using async java driver for ArangoDB?

I am trying to connect ArangoDB from my java program. I have used the official async java driver for arangodb. The document mentions that we can set the protocol using useProtocol() method. But, this method is not present in code and in javadoc as well. Can somebody tell me how can I set the protocol to HTTP?
The github document mentions this following code.
ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().useProtocol(Protocol.VST).build();
But object returned by Builder() method do not have any useProtocol() method.
This was a mistake in the documentation. The async java driver only supports VelocyStream while the sync driver supports different network protocols.

Why does the Node.JS community generally favor NoSQL over relational databases?

Why is MongoDB usually used in conjunction with NodeJS?, Is it just coincidental or are there good engineering reasons behind this combination?
There is no direct correlation between nodejs and mongo.
In particular mongo has drivers for the following languages:
C
C++
C#
Java
Node.js
Perl
PHP
Python
Ruby
Scala
The only correlation that I can find is that using nodejs queries are more similar to the same query written in the console of mongo than other languages (below an example in nodejs and in java).
In node js:
...
db.collection('restaurants').insertOne( {
"name":"Pizza Roma",
"city":"Rome",
"country":"Italy"
});
...
In java
...
Document restaurant = new Document("name", "Pizza Roma")
.append("city", "Rome")
.append("country", "Italy");
db.getCollection("restaurants").insertOne(document);
...
The structure of MongoDB documents is JSON-like.
JSON (JavaScript Object Notation) is syntactically identical to the code for creating JavaScript objects, so creating JSON structures from objects and parsing JSON to objects is really easy in JavaScript. You can directy insert a JavaScript object structure into MongoDB.
Other than that, MongoDB has Drivers for a vast array of languages.
There is no direct relation between Node.js and Mongodb. MongoDB is a
document based database which will give data as a JSON directly and it is schema less.To develop the rapid applications now a days MEAN stack apps are very famous.Actually Node.js is not limited to MongoDB it can be connected with different databases.

Mocking Repository but Then Swapping Out for Real Implementation in Node.js

I'm building a Repository layer with higher level API for my abstractions above to make calls to the database persistence. But since JavaScript doesn't have the concept of Interfaces like a language such as C# or Java does, how do you swap out the mock for the real implementation?
I prefer creating custom mocks, node repository modules with data persitence high level methods in them vs. Sinon.js or something like that.
If I'm creating node modules, then how? I could send in a mock representation of the repository where I mock out what the repository methods are doing but then the actual node modules using those repository modules would need to use the real repository implementation that calls the real database. How is this done in Node? I want to just inject via a property, I don't want some gigantic injection IoC framework either.
Since there's no concept of an interface then wtf do you do in Node/JS? I have to create a data layer below the repository (whether it be a custom set of modules making real query calls to Postgres or whether I'm using Mongoose or whatever it may be, I need a DL set of modules that the repository calls for tis real DB calls under the hood).
And lets say I do choose to use some framework like Sinon.js, what's the common interface for the module you're mocking that can be shared by the mocking framework and the real module?
There's more than one way to do it. If you come from a different background it may take some getting used to Node.
You can do this:
module.exports = function(db) {
this.db = db;
this.myQuery = function(n, cb) {
this.db.query(n, cb);
}
}
Then in config.js
var exports.db = require('./mydb');
Then
var config = require('./config.js');
var db = require('./db')(config.db);
There are lots of variations possible. You could do a dynamic require somewhere based on a string or something. Or use classes or init functions. Most are going to probably end up being similar.
The proxyrequire module could be helpful. So can Sinon.js.
Since there really isn't type checking people generally are verifying that with their tests at runtime. If you are really doing TDD it might not make a huge difference.

Resources