JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 13
  • Score
    100M100P100Q38828F
  • License MIT

Node.js driver for cockroachdb.

Package Exports

  • roachjs

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (roachjs) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

RoachJS - CockroachDB Driver

NPMNPM

Build Status

Introduction

This client is a port from the original Golang client. Internally it's is more or less the same, but this driver provides a friendlier javascript interface.

Installation

$ npm install roachjs

Documentation

Examples

Initiating a client

var Roach = require('roachjs')

var client = new Roach({
    uri: 'http://127.0.0.1:8080'
})

module.exports = client

Basic client usage I

client.get("sample_key", function(err, value, meta) {
    if(err) throw err

    client.put("other_key", value, function(err) {
        if(err) {
            // Failed
        }
        else {
            // Sucess
        }
    })
})

Advanced client usage I

// You should prepare your queries and send them in a single batch
// For optimal performance
// This actually returns you a new client
var c = client.prepare()

// This callback will be the first to be executed
c.get("sample_key", function(err, value, meta) {
    if(err) throw err

    // Do something...
})

c.get("sample_key2", function(err, value, meta) {
    if(err) throw err

    // Do something...
})

c.put("some_key", "some_value", function(err) {
    if(err) throw err

    // Do something
})

// The flush callback is the last one to be called
c.flush(function(err, meta) {
    if(err) throw err

    console.log('Sucessfuly flushed %d queries.', meta.flushed)
})

Advanced client usage II

var c = client.prepare()

// This objects (references) will be sent in place of the callback
// This pattern is a great pattern to keep your sanity :)
var dogsResp    = c.Response()
var kittensResp = c.Response()

c.get("dogs", dogsResp)
c.get("kittens", kittensResp)

c.flush(function(err) {
    if(err) throw err

    if(dogsResp.err) {
        throw new Error('failed to get dogs')
    }

    if(kittensResp.err) {
        throw new Error('failed to get kittens')
    }

    c.put("other_dogs", dogsResp.value, function(err) {
        if(err) throw err
    })

    c.put("other_kittens", kittensResp.value, function(err) {
        if(err) throw err
    })

    c.flush()
})

Advanced client usage III

var opts = {
    name: "transaction example",
}

var errNoApples = new Error('Insufficient apples!')

var transaction = function(txn, commit, abort) {
    var applesInStock = txn.Response()

    txn.get("applesInStock", applesInStock)

    txn.flush(function(err) {
        if(err || applesInStock.err) {
            return abort(err)
        }

        var dispatch = 5
        var inStock = ParseInt(applesInStock.value)

        if(inStock < dispatch) {
            return abort(errNoApples)
        }

        txn.increment("applesInStock", -dispatch)
        txn.increment("applesInRoute", +dispatch)

        // Commit automatically flushes
        commit()
    })
}

client.runTransaction(opts, transaction, function(err, meta) {
    if(err === errNoApples) {
        // Alert user there are no more apples...
    }
    else if(err) {
        // Transaction failed...
    }
    else {
        // Transaction commited...
    }
})

Interface

new Client(opts)

Returns a new roachjs client with options.

Parameters

name type description
opts object see

Client options

opt description default
uri uri to the cockroach http endpoint http://127.0.0.1:8080/
host host or ip to the cockroach http endpoint 127.0.0.1
port port to the cockroach http endpoint 8080
ssl connect throught https false
user user to run the requests with root
retry retry requests when cockroach responds with a busy signal true
http http module to use require('http')
clock clock module to use new Date()

Methods

method
get
put
conditionalPut
contains
increment
scan
delete
deleteRange
prepare
runTransaction

client.get(key, callback)

Gets a single entry from the datastore, specified by key.

Parameters

name type description
key string
callback callback function(err, value, meta) {}

Callback

name type description
err Error()
value string
meta object see

Example

client.get("key", function(err, value, meta) {})

client.put(key, value, callback)

Puts a value in the datastore in the specified key.

Parameters

name type description
key string
value string
callback callback function(err, meta) {}

Callback

name type description
err Error()
meta object see

Example

client.put("key", "value", function(err, meta) {})

client.conditionalPut(key, value, ifValue, callback)

ConditionalPut sets the value for a key if the existing value matches the ifValue. Specifying an empty or null ifValue means the entry must not yet exist.

Parameters

name type description
key string
value string
ifValue string, null use null to put if entry doens't exists
callback callback function(err, meta) {}

Callback

name type description
err Error()
meta object see

Example

client.conditionalPut("status", "running", "stopped", function(err, meta) {})
client.conditionalPut("status", "new", null, function(err, meta) {})

client.contains(key, callback)

Contains determines if a key exists in the datastore.

Parameters

name type description
key string
callback callback function(err, exists, meta) {}

Callback

name type description
err Error()
exists boolean
meta object see

Example

client.contains("john", function(err, exists, meta) {
    if(exists === true) {
        // john exists in the datastore
    }
})

client.increment(key, increment, callback)

Increment increments the value at the specified key by some increment value. Once called for a key, Put & Get will return errors; only Increment will continue to be a valid command. The value must be deleted before it can be reset using Put.

Parameters

name type description
key string
increment integer
callback callback function(err, newValue, meta) {}

Callback

name type description
err Error()
newValue integer the new value for this counter, after the increment operation
meta object see

Example

client.increment("counter", 5, function(err, newValue, meta) {
    console.log('counter current value is', newValue)
})

client.scan(start_key, end_key, limit, callback)

Scan the datastore for keys in the range of the start_key and end_key, limiting the result by limit.

Parameters

name type description
key string
start_key string
end_key string
limit integer
callback callback function(err, newValue, meta) {}

Callback

name type description
err Error()
results array
meta object see

Example

client.scan("a", "Z", 100, function(err, results, meta) {
    for(value as results) {
        console.log(value)
    }
})

client.delete(key, callback)

Delete an entry from the datastore specified by key.

Parameters

name type description
key string
callback callback function(err, meta) {}

Callback

name type description
err Error()
meta object see

Example

client.delete("key", function(err, meta) {})

client.deleteRange(start_key, end_key, limit, callback)

Delete all keys found in a range, from start_key to end_key, limited by limit.

Parameters

name type description
key string
start_key string
end_key string
limit integer
callback callback function(err, deleted, meta) {}

Callback

name type description
err Error()
deleted integer number of entries deleted
meta object see

Example

client.deleteRange("a", "Z", 100, function(err, deleted, meta) {
    console.log('deleted %d entries', deleted)
})

client.prepare()

Return you a new prepared client. It inherits all the methods from the original client. Read Advanced client usage II and Advanced client usage III to understand how to use this client.

Methods

method description
flush Flush the prepared queries
Response see

Example

var c = client.prepare()

c.get("key", function(err, value, meta) {
    // Do something...
})

c.get("key2", function(err, value, meta) {
    // Do something...
})

c.put("key3", "value", function(err, meta) {
    // Do something...
})

c.flush()

client.flush(callback)

Flush the prepared queries buffer, and send it as a batch request.

Parameters

name type description
callback callback optional

Callback

name type description
err Error() batch request failed
meta object see

Example

client.flush(function(err, meta) {
    if(err) {
        // Flush failed..
    }
    else {
        console.log('flushed %d queries.', meta.flushed)
    }
})

client.Response()

Flush the prepared queries buffer, and send it as a batch request. Read Advanced client usage III to learn how to use this pattern.

Returns

Returns an response object.

property type description
err Error() is null if no error was returned
value string, number, boolean general response value
meta object see

client.runTransaction(opts, transaction, callback)

RunTransaction executes a retryable transaction function in the context of a distributed transaction. The transaction is automatically aborted if retryable function returns any error aside from recoverable internal errors, and is automatically committed otherwise. retryable should have no side effects which could cause problems in the event it must be run more than once. The opts contains transaction settings.

Parameters

name type description
opts object options
transacation retryable function function(txn, commit, abort) {}
callback callback function(err, meta) {}

Transaction options

opt description default
name transaction name for debugging ""
isolation 0

Callback

name type description
err Error() if transaction fails
meta object see

Extra

Meta properties

The meta argument contains information about the request response, and any other extra information data about the returned value.

Properties

property type description
timestamp integer timestamp of the returned entry
wall_time integer timestamp of when the read or write operation was performed
flushed integer number of flushed queries

Transaction function

The transaction function is an retryable function, it may be executed more than once. This function should never forget to call commit or abort. Throwing an error inside this function also aborts the transaction.

Arguments

name type description
txn Prepared client this client is the same as client.prepare(), you can flush yourself if you don't wan't to commit yet.
commit callback to try to commit transaction
abort callback to abort transaction
  • abort() accepts an optional Error. This error will be passed to the .runTransaction callback.

Example

var transaction = function(txn, commit, abort) {
    for(var i = 0; i < 100; i++) {
        var key = i.toString()

        // Provide an txn.Response()
        // just so it won't trow an error
        txn.put(key, "hello", txn.Response())
    }

    // Commit automatically flushes
    // the prepared transaction.
    commit()
}

Contributors