Skip to content

Instantly share code, notes, and snippets.

@aseemk
Created November 10, 2014 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aseemk/9ea5db2dde4e44c1f289 to your computer and use it in GitHub Desktop.
Save aseemk/9ea5db2dde4e44c1f289 to your computer and use it in GitHub Desktop.
Neo4j transaction test.
echo = console.log
Request = require 'request'
BASE_URL = 'http://localhost:7474'
# helper to make transactional requests:
req = (_, {query, params, commit, rollback, txId}) ->
method = if rollback then 'DELETE' else 'POST'
url = "#{BASE_URL}/db/data/transaction"
url += "/#{txId}" if txId
url += '/commit' if commit
json =
statements: [
statement: query
parameters: params
]
headers =
'X-Stream': 'true'
resp = Request {method, url, json}, _
echo JSON.stringify $(resp).pick('statusCode', 'headers', 'body'), null, 4
resp
echo '\nSetup: Create a random test node.'
{body} = req _,
query: 'CREATE (n:Test) RETURN ID(n)'
commit: true
nodeId = body.results[0].data[0].row[0] # so gross
echo "Test node: #{nodeId}"
echo '\nStep 1: Begin a transaction.'
{headers} = req _,
query: 'START n=node({id}) RETURN ID(n)'
params: {id: nodeId}
commit: false
txId = headers.location.split('/').pop()
echo "Transaction ID: #{txId}"
# # DELETE TEST: This fails as expected.
# # Neo.ClientError.Statement.EntityNotFound.
#
# echo '\nStep 2: In a separate, parallel transaction, make a conflicting query.'
# req _,
# query: 'START n=node({id}) DELETE n'
# params: {id: nodeId}
# commit: true
# echo 'Test node deleted.'
#
# echo '\nStep 3: Back in the original transaction, attempt to commit.'
# req _,
# query: 'START n=node({id}) RETURN ID(n)'
# params: {id: nodeId}
# commit: true
# txId: txId
# WRITE TEST: This *doesn't* fail as expected! Result: 'nullbaz'.
# ==> Takeaway: transactions aren't a silver bullet for business logic.
echo '\nStep 2: In that transaction, make a read.'
{body} = req _,
query: 'START n=node({id}) RETURN n.foo'
params: {id: nodeId}
txId: txId
fooProp1 = body.results[0].data[0].row[0]
echo "Property read: #{fooProp1}"
echo '\nStep 3: In a separate, parallel transaction, make a concurrent write.'
{body} = req _,
query: 'START n=node({id}) SET n.foo = {foo} RETURN n.foo'
params: {id: nodeId, foo: 'bar'}
commit: true
fooProp2 = body.results[0].data[0].row[0]
echo "Property written: #{fooProp2}"
echo '\nStep 4: Back the original transaction,
make a concurrent write based on the original read, and commit.'
{body} = req _,
query: 'START n=node({id}) SET n.foo = {foo} RETURN n.foo'
params: {id: nodeId, foo: fooProp1 + 'baz'}
commit: true
txId: txId
fooProp3 = body.results[0].data[0].row[0]
echo "Property written again: #{fooProp3}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment