Example #1
0
var executeQueries = function(host, port, user, password, db, queries, options, cb) {
	
	var client = new cassandra.Client({
		contactPoints: [host], 
		authProvider: new cassandra.auth.PlainTextAuthProvider(user, password),
		keyspace: db,
		protocolOptions: {
			port: port
		}
	});

	client.connect(function(err){
		if(err) return cb(err);
		
		var result = [];

		async.eachSeries(queries, function(query, callback) {
			client.execute(query, function(err, rows) {

				if (err) 
					result.push(new Error(err));
				else 
					result.push(formatOutput(rows.rows));

				return callback();
			});
		}, function() {
			client.shutdown(function () {
				return cb(null, result);
			});
		});
	});
};
/**
 * Inserts multiple rows in a table from an Array using the built in method <code>executeConcurrent()</code>,
 * limiting the amount of parallel requests.
 */
async function example() {
  await client.connect();
  await client.execute(`CREATE KEYSPACE IF NOT EXISTS examples
                        WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1' }`);
  await client.execute(`USE examples`);
  await client.execute(`CREATE TABLE IF NOT EXISTS tbl_sample_kv (id uuid, value text, PRIMARY KEY (id))`);

  // The maximum amount of async executions that are going to be launched in parallel
  // at any given time
  const concurrencyLevel = 32;

  // Use an Array with 10000 different values
  const values = Array.from(new Array(10000).keys()).map(x => [ Uuid.random(), x.toString() ]);

  try {

    const query = 'INSERT INTO tbl_sample_kv (id, value) VALUES (?, ?)';
    await executeConcurrent(client, query, values);

    console.log(`Finished executing ${values.length} queries with a concurrency level of ${concurrencyLevel}.`);

  } finally {
    client.shutdown();
  }
}
Example #3
0
    config: function (addr, dbname, opts, callback) {
      if (!initFlag) {

        var addressArr = [];
        if( typeof addr == 'string' ){
          addressArr.push( addr );
        } else if ( Array.isArray(addr) ){
          addressArr = addressArr.concat( addr );
        }

        var keyspace = dbname ? dbname : 'xpush';

        client = new cassandra.Client( { contactPoints: addressArr, keyspace, keyspace } );
        client.connect( function( err, result){
          if( err ){
            console.log( ( err.message.indexOf( "Keyspace" ) > -1 && err.message.indexOf( "does not exist" ) > -1  ) );
            if (callback) callback(err);
          } else {
            initFlag = true;
            if (callback) callback(null, client);
          }
        });
      } else {
        if (callback) callback(null, client);
      }
    }
Example #4
0
 // conect to DB
 function (callback) {
     client.connect(function (err) {
         if (err) {
             console.log('Problem connecting to database: ' + err);
             console.log("finish due error on client");
             finish(-1);
         } else {
             console.log('   Connected to DB');
         }
         callback(null);
     });
 },
Example #5
0
 connect(...args) {
   if (args.length > 0 && _.isFunction(args[args.length - 1])) {
     return this.client.connect(...args)
   }
   else {
     try{
       return this._connectSync(...args)
     } catch (e){
       console.error('Error connecting to',e)
     }
   }
 }
Example #6
0
function wait4cassandra() {
    client.connect(function(err) {
    if(err) {
          console.log("*** still waiting for cassandra")
          if(err.toString().indexOf("sparkoin") == -1)
            setTimeout(wait4cassandra, 3000)
	        else
	          setTimeout(checkTable, 1000);
        } else {
	       checkTable()
	    }
    })
}
Example #7
0
 it("should init a store with a custom client", function (done)
 {
     var customClient = new cassandra.Client(options.clientOptions);
     var opts = {
         table: "express_session",
         client: customClient
     };
     customClient.connect(function (error)
     {
         assert.equal(error, null);
         store = new CassandraStore(opts);
         assert(typeof store.client === "object");
         assert.equal(store.client.keyspace, options.clientOptions.keyspace);
         done();
     });
 });
Example #8
0
Cassandra.prototype._executeSchemaQueries = function(){

  var self = this;
  var deferred = Q.defer();
  var schemaFile;
  var cass;

  w.log('Executing schema queries');

  if(self.schemaName){

    schemaFile = path.join( __dirname, '../models/', self.schemaName );

    cass = new cassandra.Client({
      contactPoints: self._clientOptions.contactPoints,
      keyspace: null
    });

    cass.connect(function(err, result) {
      if(err){
        throw new Error('Could not connect to Cassandra', err);
      }
      console.log('Executing commands from', schemaFile);

      // parse contents
      var text = fs.readFileSync(schemaFile, {encoding: self.schemaEncoding});

      // remove new lines
      var trimmed_text = text.replace(/(\r\n|\n|\r)/gm,"");

      // split queries as does not work when batched
      var queries = trimmed_text.split(';');

      self._executeManyWithClient(queries,cass).then(function(){
        cass.shutdown(function(){
          deferred.resolve();
        });
      }).done();

    });

  } else {
    deferred.resolve();
  }

  return deferred.promise;
};
Example #9
0
var testConnection = function(host, port, user, password, db, options, cb) {
	// var contactPoints = host.split(',');

	var client = new cassandra.Client({
		contactPoints: [host], 
		authProvider: new cassandra.auth.PlainTextAuthProvider(user, password),
		keyspace: db,
		protocolOptions: {
			port: port
		}
	});

	client.connect(function(err){
		if(err) return cb(err);
		client.shutdown(function(){
			return cb();
		})
	});
};
Example #10
0
router.put('/cql', (req, res, next) => {
  if (!req.body.cql || !req.body.username || !req.body.password) {
    return res.status(400).end();
  }

  var client = new cassandra.Client({
    contactPoints: config.development.hosts,
    authProvider: new cassandra.auth.PlainTextAuthProvider(
      req.body.username,
      req.body.password
    ),
  });

  client.connect(err => {
    if (err) {
      return next(err);
    }

    runQuery(res, req.body.cql.split(';'), 0, next, client);
  });

});
function setupWorkspace() {
	var client = new cassandra.Client({
		contactPoints : [ '127.0.0.1' ]
	});
	client .connect(function(err) {
		if (!err) {
			client.execute("USE nosqllab", [], function(err){
				errorHandler(err, "use nosqllab", true);
				client.execute("CREATE TABLE user(id int, reputation int, created timestamp, displayName text, "
						+ " accountId int, PRIMARY KEY(id))", function(err){
					errorHandler(err, "create user table", true);
					process.exit(0);
				});
			});
			
		} else {
			errorHandler(err, "Connect: ");
		}
	});
	client.shutdown(function(err) { // do nothing
	});
}
Example #12
0
var express = require('express');
var router = express.Router();
var cassandra = require('cassandra-driver');

var client = new cassandra.Client({contactPoints : ['127.0.0.1']});
client.connect(function(err, result){
    console.log('cassandra connected: addshout');
});


router.post('/', function(req, res){
	var id1 = cassandra.types.uuid();
	var id2 = cassandra.types.timeuuid();

	var queries = [
		{
			query: 'INSERT INTO shoutapp.shouts(shout_id, username, body) VALUES(?,?,?)',
			params:[id1, req.body.username, req.body.body]
		},
		{
			query: 'INSERT INTO shoutapp.usershouts(username, shout_id, body) VALUES(?,?,?)',
			params: [req.body.username, id2, req.body.body]
		}
	];
	queryOptions = {};
	client.batch(queries, queryOptions, function(err){
		console.log(err);
		res.redirect('/shouts');
	});
});
const cassandra = require('cassandra-driver');
const authProvider = new cassandra.auth.PlainTextAuthProvider('myklovr', 'myklovr');
const client = new cassandra.Client({ contactPoints: ['8.34.214.12'],authProvider: authProvider });
client.connect(function (err) {
    console.log(err);
});

exports.executeQuery = function(query,callback,connId,params){
    console.log('executing query');
    client.execute(query, params, function (err, result) {
        callback(connId,result,err);
    })
}
Example #14
0
const cassandra = require('cassandra-driver');

var database = require('../config/database');

const client = new cassandra.Client({
    contactPoints: [database.cassandra.url],
    keyspace: database.cassandra.keyspace
});
client.connect(function (err) {
    if (err) console.log("***ERROR*** \n Could not Connect to Cassandra \n" + err);
});

function ntos(n) {
    return n > 9 ? "" + n : "0" + n;
}

//<<<<<<< HEAD
module.exports.getData = function (req, res, params) {
    //splitting the request string in ','. Parameters go like this: ApartmentID + ViewMode (monthly, daily...) + dateFrom + dateTo
    var parameters = params.split(",");
    var apartmentID = "'" + parameters[0] + "'";
    var viewMode = parameters[1];
    var dateFrom = parameters[2];
    var dateTo = parameters[3];
    //    console.log("Parameters :" + parameters);
    //    console.log("SELECT * FROM " + viewMode + " WHERE");

    //send query to cassandra database.
    client.execute("SELECT * FROM " + viewMode + " WHERE id=" + apartmentID + " AND ts>='" + dateFrom + "' AND ts<='" + dateTo + "'", function (err, result) {
        if (!err) {
            if (result.rows.length > 0) {
Example #15
0
var express = require('express');
var router = express.Router();
var request = require('request');
var cassandra = require('cassandra-driver');

var globals = require('../globals');

var client = new cassandra.Client({contactPoints: [globals.ip, '130.237.37.60', '130.237.37.99']}); // ip here if not localhost
client.connect(function(err, res) {
  console.log('index: cassandra connected');
});

/* GET home page. */
router.get('/', function(req, res, next) {
  var query = "SELECT DISTINCT subreddit, link_id FROM reddit.comments";
  console.log('?search=' + req.query.search);
  if (req.query.search !== undefined && req.query.search !== "")
    query += " WHERE subreddit = '" + req.query.search + "'";
  client.execute(query, [], function(err, result) {
    //var end = now();
    //var time = (end-start).toFixed(1);
    res.render('index', {
      results: result.rows
    });
  });
});

router.get('/s', function(req, res, next) {
  request.post({
    headers: {'content-type' : 'application/x-www-form-urlencoded'},
    url: 'http://' + globals.ip + ':8090/jobs?appName=sql&classPath=spark.jobserver.GetSubreddits&context=cassandra-context&sync=true',
Example #16
0
var express = require('express');
var router = express.Router();
var cassandra = require('cassandra-driver');

var client = new cassandra.Client({ contactPoints: ['127.0.0.1'] });
client.connect(function(err, result) {});

router.get('/add', function(req, res, next) {
  res.render('addcategory');
});

router.post('/add', function(req, res, next) {
	var cat_id = cassandra.types.uuid();
	var query = 'insert into findadoc.categories (cat_id, name) values (?, ?)';
	client.execute(query, [cat_id, req.body.name], {prepare: true}, function(err, result) {
		if (err) {
			res.status(404).send({ msg: err });
		} else {
			req.flash('success', 'Category added.');
			res.location('/doctors');
			res.redirect('/doctors');
		}
	});
});

module.exports = router;
Example #17
0
DatastaxDriver.prototype.createConnectionPool = function createConnectionPool(poolConfig, waitForConnect, callback) {
  var self          = this,
    openRequestId = uuid.v4(),
    pool;

  self.logger.debug('priam.Driver: Creating new pool', {
    poolConfig: {
      keyspace: poolConfig.keyspace,
      contactPoints: poolConfig.contactPoints
    }
  });

  var dsPoolConfig = _.cloneDeep(poolConfig);
  if (dsPoolConfig.username && dsPoolConfig.password) {
    dsPoolConfig.authProvider = new cqlDriver.auth.PlainTextAuthProvider(dsPoolConfig.username, dsPoolConfig.password);
  }

  dsPoolConfig.queryOptions = dsPoolConfig.queryOptions || {};
  dsPoolConfig.queryOptions.fetchSize = dsPoolConfig.limit;
  dsPoolConfig.queryOptions.prepare = false;
  if (dsPoolConfig.consistencyLevel) {
    dsPoolConfig.queryOptions.consistency = dsPoolConfig.consistencyLevel;
  }
  var port = null;
  if (Array.isArray(dsPoolConfig.contactPoints)) {
    for (var i = 0; i < dsPoolConfig.contactPoints.length; i++) {
      var split = dsPoolConfig.contactPoints[i].split(':');
      dsPoolConfig.contactPoints[i] = split[0].trim();
      if (split.length > 1) {
        port = parseInt(split[1].trim(), 10);
      }
    }
    if (port !== null) {
      dsPoolConfig.protocolOptions = dsPoolConfig.protocolOptions || {};
      dsPoolConfig.protocolOptions.port = port;
    }
  }

  if (poolConfig.getAConnectionTimeout) {
    dsPoolConfig.socketOptions = dsPoolConfig.socketOptions || {};
    dsPoolConfig.socketOptions.connectTimeout = poolConfig.getAConnectionTimeout;
  }

  if (poolConfig.poolSize) {
    dsPoolConfig.pooling = dsPoolConfig.pooling || {};
    dsPoolConfig.pooling.coreConnectionsPerHost = dsPoolConfig.pooling.coreConnectionsPerHost || {};
    dsPoolConfig.pooling.coreConnectionsPerHost[cqlDriver.types.distance.local.toString()] = poolConfig.poolSize;
    dsPoolConfig.pooling.coreConnectionsPerHost[cqlDriver.types.distance.remote.toString()] = Math.ceil(poolConfig.poolSize / 2);
  }

  pool = new cqlDriver.Client(dsPoolConfig);
  pool.storeConfig = poolConfig;
  pool.waiters = [];
  pool.isReady = false;
  pool.on('log', function (level, message, data) {
    self.emit('connectionLogged', level, message, data);
    // unrecoverable errors will yield error on execution, so treat these as warnings since they'll be retried
    // treat everything else as debug information.
    var logMethod = (level === 'error' || level === 'warning') ? 'warn' : 'debug';

    var metaData = {
      datastaxLogLevel: level
    };
    if (typeof data === 'string') {
      message += ': ' + data;
    } else {
      metaData.data = data;
    }
    self.logger[logMethod]('priam.Driver.' + message, metaData);
  });

  this.emit('connectionOpening', openRequestId);
  pool.connect(function (err) {
    if (err) {
      self.emit('connectionFailed', openRequestId, err);
      self.logger.error('priam.Driver: Pool Connect Error',
        { name: err.name, error: err.message, inner: err.innerErrors });
      if (waitForConnect) {
        callback(err, pool);
      }
      self.callWaiters(err, pool);
      return void self.closePool(pool);
    }
    pool.isReady = true;
    self.emit('connectionOpened', openRequestId);
    if (waitForConnect) {
      callback(null, pool);
    }
    self.callWaiters(null, pool);
  });
  if (!waitForConnect) {
    callback(null, pool);
  }
};
Example #18
0
// set up ======================================================================
var express  = require('express');
var app      = express(); 								// create our app w/ express
var port  	 = process.env.PORT || 5002; 				// set the port
var database = require('./config/database'); 			// load the database config
var cassandra = require('cassandra-driver');
var morgan   = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

var dbCli = new cassandra.Client(database);
dbCli.connect(function(err){
    if (err) {
        console.log('could not connect to cassandra: ' + err.message)
        process.exit(1);
    }
    console.log('connected to cassandra')
});

// configuration ===============================================================
app.use(express.static(__dirname + '/app')); 		// set the static files location /public/img will be /img for users
app.use('/bower_components', express.static('bower_components'));
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request

// routes ======================================================================
require('./server/routes.js')(app, dbCli);
Example #19
0
function createClient (config, next) {

  var cassandraConfig = config && config.cassandra;
  var client = new cassandra.Client(cassandraConfig);
  client.on('log', function (level, className, message, furtherInfo) {
    debugDriver('log event: %s -- %s', level, message);
  });

  function get (query, data, options, next) {
    if (!next) { next = options; options = null; }
    if (!next) { next = data; data = null; }
    if (!query) { return next(null); }
    debug('get', query, data);
    client.execute(query, data, options, function (err, result) {
      if (err) { return next(err); }
      next(null, result && result.rows ? result.rows[0] : null);
    });
  }

  function execute (query, data, options, next) {
    if (!next) { next = options; options = null; }
    if (!next) { next = data; data = null; }
    if (!query) { return next(null); }
    debug('execute', query, data);
    client.execute(query, data, options, function (err, result) {
      if (err) { return next(err); }
      next(null, result && result.rows ? result.rows : null);
    });
  }

  function generateId (uuid) {
    if (uuid) {
      if (isUuid(uuid)) {
        return uuid;
      } else {
        return Uuid.fromString(uuid);
      }
    } else {
      return Uuid.random();
    }
  }

  function generateTimeId (timestamp) {
    if (timestamp) {
      return TimeUuid.fromDate(timestamp);
    } else {
      return TimeUuid.now();
    }
  }

  function isUuid (value) {
    return value instanceof Uuid;
  }

  function isStringUuid (value) {
    return (typeof value === 'string' && value.length === 36 && (value.match(/-/g) || []).length === 4);
  }

  function isValidId (value) {
    return isUuid(value) || isStringUuid(value);
  }

  function formatId (value) {
    if (isUuid(value)) {
      return value;
    } else {
      return generateId(value);
    }
  }

  function getTimestamp (value) {
    return value ? new Date(value) : new Date();
  }

  client.connect(function () {
    next(null, {
      type: 'cassandra',
      config: cassandraConfig,
      _client: client,
      get: get,
      execute: execute,
      generateId: generateId,
      generateTimeId: generateTimeId,
      isValidId: isValidId,
      formatId: formatId,
      getTimestamp: getTimestamp,
      migrations: path.resolve(__dirname, 'migrations'),
      queries: require('./queries'),
      setup: require('./setup')
    });
  });

}
"use strict";
var cassandra = require('cassandra-driver');

var client = new cassandra.Client({ contactPoints: ['127.0.0.1']});

client.connect(function (err) {
  if (err) {
    client.shutdown();
    return console.error('There was an error when connecting', err);
  }
  console.log('Connected, listing keyspaces:');
  for (var name in client.metadata.keyspaces) {
    if (!client.metadata.keyspaces.hasOwnProperty(name)) continue;
    var keyspace = client.metadata.keyspaces[name];
    console.log('- %s:\n\tstrategy %s\n\tstrategy options %j', keyspace.name, keyspace.strategy,  keyspace.strategyOptions);
  }
  console.log('Shutting down');
  client.shutdown();
});
"use strict";
var cassandra = require('cassandra-driver');

const client = new cassandra.Client({ contactPoints: ['127.0.0.1'] });
client.connect()
  .then(function () {
    console.log('Connected, listing keyspaces:');
    for (var name in client.metadata.keyspaces) {
      if (!client.metadata.keyspaces.hasOwnProperty(name)) continue;
      var keyspace = client.metadata.keyspaces[name];
      console.log('- %s:\n\tstrategy %s\n\tstrategy options %j',
        keyspace.name, keyspace.strategy,  keyspace.strategyOptions);
    }
    return client.shutdown();
  })
  .catch(function (err) {
    console.error('There was an error when connecting', err);
    return client.shutdown();
  });
Example #22
0
//BASIC SETUP 
//===============================================================================

//Calling required packages
var express = require("express");
var cassandra = require("cassandra-driver");
var app = express();

//Initialising connection to Nosql Cassandra database
var client = new cassandra.Client( { contactPoints : [ '128.16.80.125' ], keyspace : 'orangesystem'} );
client.connect(function(err, result) {
    console.log('Connected.');
});


app.set('port', process.env.PORT || 1995 ); //setting port number for local testing


var router = express.Router();

// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
	console.log('An API request received...');
    res.header("Access-Control-Allow-Origin", "*");
 	res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
 	res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
    
    if (req.method == 'OPTIONS') {
    	return res.sendStatus(200);
    }
Example #23
0
var express = require('express');
var router = express.Router();
var cassandra = require('cassandra-driver');

var client = new cassandra.Client({
    contactPoints:['127.0.0.1']
});

client.connect(function(err, result){
    console.log('Cassandra Connected');
});


router.get('/add', function(req, res, next) {
  res.render('addcategory');
});

router.post('/add', function(req, res, next) {

    console.log("WE ARE HERE");

  var cat_id = cassandra.types.uuid();
  var query = "INSERT INTO findadoc.categories(cat_id, name) VALUES(?,?)";

  client.execute(query, [cat_id, req.body.name], {prepare: true},
  function(err, result){
      if(err){
          res.status(404).send({msg:err});
      } else {
          req.flash('success', "Category Added");
          res.location('/doctors');
 function connect(next) {
     client.connect(next);
 },
"use strict";
var cassandra = require('cassandra-driver');

var client = new cassandra.Client({ contactPoints: ['127.0.0.1']});

client.connect(function (err) {
  if (err) {
    client.shutdown();
    return console.error('There was an error when connecting', err);
  }
  console.log('Connected to cluster with %d host(s): %j', client.hosts.length, client.hosts.keys());
  console.log('Keyspaces: %j', Object.keys(client.metadata.keyspaces));
  console.log('Shutting down');
  client.shutdown();
});
Example #26
0
var express = require('express');
var router = express.Router();
var cassandra = require('cassandra-driver');

var client = new cassandra.Client({contactPoints : ['127.0.0.1']});
client.connect(function(err, result){
    console.log('cassandra connected: users');
});

var getAllUsers = 'SELECT * FROM shoutapp.users';

/* GET users listing. */
router.get('/', function(req, res) {
  client.execute(getAllUsers,[], function(err, result){
  	if(err){
  		res.status(404).send({msg: err});
  	} else {
  		//res.json(result);
  		res.render('users',{
  			users: result.rows
  		});
  	}
  });
});

module.exports = router;
Example #27
0
  repository.getCommentsByVideo(req.params.videoId, function (err, comments) {
    if (err) return next(err);
    res.json(comments);
  });
});
app.post('/v1/comment/:videoId([a-f0-9\\-]{36})', function (req, res, next) {
  repository.insertComment(req.params.videoId, req.body.userId, req.body.comment, function (err, id) {
    if (err) return next(err);
    res.send(id.toString());
  });
});
app.get('/v1/rating/:videoId([a-f0-9\\-]{36})', function (req, res, next) {
  repository.getRating(req.params.videoId, function (err, rating) {
    if (err) return next(err);
    res.json(rating);
  });
});
app.post('/v1/rating/:videoId([a-f0-9\\-]{36})', function (req, res, next) {
  repository.setRating(req.params.videoId, req.body.userId, req.body.value, function (err) {
    if (err) return next(err);
    res.end();
  });
});
client.connect(function (err) {
  if (err) {
    console.error('Cassandra driver was not able to connect to %s: %s', contactPoint, err);
  }
  var server = app.listen(8080, function () {
    console.log('App listening at http://%s:%s', 'localhost', server.address().port);
  });
});
function makeClient(options) {
    const clientOpts = {};
    const conf = options.conf;
    validateAndNormalizeDcConf(conf);

    clientOpts.keyspace = conf.keyspace || 'system';
    clientOpts.contactPoints = conf.hosts;

    // See http://www.datastax.com/drivers/nodejs/2.0/module-policies_loadBalancing-DCAwareRoundRobinPolicy.html
    clientOpts.policies = {
        loadBalancing: new loadBalancing.TokenAwarePolicy(
            new loadBalancing.DCAwareRoundRobinPolicy(conf.localDc)
        ),
        // Also see
        // http://www.datastax.com/documentation/developer/nodejs-driver/2.0/common/drivers/reference/clientOptions.html
        // Retry immediately, then delay by 100ms, back off up to 120s
        reconnection: new reconnection.ExponentialReconnectionPolicy(100, 120000, true)
    };

    if (conf.tls) {
        try {
            clientOpts.sslOptions = sslOptions(conf.tls);
        } catch (e) {
            return P.reject(e);
        }
    }

    // Increase the schema agreement wait period from the default of 10s
    clientOpts.protocolOptions = {
        maxSchemaAgreementWaitSeconds: 30,
        maxVersion: 3
    };

    if (conf.username && conf.password) {
        clientOpts.authProvider = new cass.auth.PlainTextAuthProvider(
                conf.username, conf.password);
    }

    // Up the maximum number of prepared statements. Driver default is 500.
    clientOpts.maxPrepared = conf.maxPrepared || 50000;
    clientOpts.promiseFactory = P.fromCallback;

    const client = new cass.Client(clientOpts);

    client.on('log', (level, message, info) => {
        // Re-map levels
        /* eslint-disable indent */
        switch (level) {
            case 'warning':
                level = 'warn';
                break;
            case 'verbose':
                level = 'trace';
                break;
            default:
                break; // other levels correspond to ours
        }
        /* eslint-enable indent */

        level += '/table/cassandra/driver';
        options.log(level, {
            message,
            info
        });
    });

    return client.connect()
    .then(() => new DB(client, options));
}
Example #29
0
const config = require('../../config').databases;
const cassandra = require('cassandra-driver');
const SshClient = require('node-ssh');

const client = new cassandra.Client({
  contactPoints: config.development.hosts,
  authProvider: new cassandra.auth.PlainTextAuthProvider(
    config.development.cassandra.username,
    config.development.cassandra.password
  ),
});

client.connect(function(err, result) {
  if (err) {
    console.log('Cassandra connection error:' + err);
  } else {
    console.log('Connected to cassandra server');
  }
});

function execute(code, qClient) {
  if (!code) {
    return Promise.resolve();
  }

  qClient = qClient || client;

  return new Promise((resolve, reject) => {
    console.log('[CASSANDRA]', code);
    qClient.execute(code, (err) => {
      if (err) {