Build a Node.js App with CockroachDB

This tutorial shows you how build a simple Node.js application with CockroachDB using a PostgreSQL-compatible driver or ORM.

We have tested the Node.js pg driver and the Sequelize ORM enough to claim beta-level support, so those are featured here. If you encounter problems, please open an issue with details to help us make progress toward full support.

Before you begin

Step 1. Install Node.js packages

To let your application communicate with CockroachDB, install the Node.js pg driver:

  1. $ npm install pg

The example app on this page also requires async:

  1. $ npm install async

Step 2. Create the maxroach user and bank database

Start the built-in SQL client:

  1. $ cockroach sql --certs-dir=certs

In the SQL shell, issue the following statements to create the maxroach user and bank database:

  1. > CREATE USER IF NOT EXISTS maxroach;
  1. > CREATE DATABASE bank;

Give the maxroach user the necessary permissions:

  1. > GRANT ALL ON DATABASE bank TO maxroach;

Exit the SQL shell:

  1. > \q

Step 3. Generate a certificate for the maxroach user

Create a certificate and key for the maxroach user by running the following command. The code samples will run as this user.

  1. $ cockroach cert create-client maxroach --certs-dir=certs --ca-key=my-safe-directory/ca.key

Step 4. Run the Node.js code

Now that you have a database and a user, you'll run code to create a table and insert some rows, and then you'll run code to read and update values as an atomic transaction.

Basic statements

First, use the following code to connect as the maxroach user and execute some basic SQL statements, creating a table, inserting rows, and reading and printing the rows.

Download the basic-sample.js file, or create the file yourself and copy the code into it.

  1. var async = require('async');
  2. var fs = require('fs');
  3. var pg = require('pg');
  4. // Connect to the "bank" database.
  5. var config = {
  6. user: 'maxroach',
  7. host: 'localhost',
  8. database: 'bank',
  9. port: 26257,
  10. ssl: {
  11. ca: fs.readFileSync('certs/ca.crt')
  12. .toString(),
  13. key: fs.readFileSync('certs/client.maxroach.key')
  14. .toString(),
  15. cert: fs.readFileSync('certs/client.maxroach.crt')
  16. .toString()
  17. }
  18. };
  19. // Create a pool.
  20. var pool = new pg.Pool(config);
  21. pool.connect(function (err, client, done) {
  22. // Close communication with the database and exit.
  23. var finish = function () {
  24. done();
  25. process.exit();
  26. };
  27. if (err) {
  28. console.error('could not connect to cockroachdb', err);
  29. finish();
  30. }
  31. async.waterfall([
  32. function (next) {
  33. // Create the 'accounts' table.
  34. client.query('CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT);', next);
  35. },
  36. function (results, next) {
  37. // Insert two rows into the 'accounts' table.
  38. client.query('INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250);', next);
  39. },
  40. function (results, next) {
  41. // Print out account balances.
  42. client.query('SELECT id, balance FROM accounts;', next);
  43. },
  44. ],
  45. function (err, results) {
  46. if (err) {
  47. console.error('Error inserting into and selecting from accounts: ', err);
  48. finish();
  49. }
  50. console.log('Initial balances:');
  51. results.rows.forEach(function (row) {
  52. console.log(row);
  53. });
  54. finish();
  55. });
  56. });

Then run the code:

  1. $ node basic-sample.js

The output should be:

  1. Initial balances:
  2. { id: '1', balance: '1000' }
  3. { id: '2', balance: '250' }

Transaction (with retry logic)

Next, use the following code to again connect as the maxroach user but this time execute a batch of statements as an atomic transaction to transfer funds from one account to another and then read the updated values, where all included statements are either committed or aborted.

Download the txn-sample.js file, or create the file yourself and copy the code into it.

Note:

With the default SERIALIZABLE isolation level, CockroachDB may require the client to retry a transaction in case of read/write contention. CockroachDB provides a generic retry function that runs inside a transaction and retries it as needed. The code sample below shows how it is used.

  1. var async = require('async');
  2. var fs = require('fs');
  3. var pg = require('pg');
  4. // Connect to the bank database.
  5. var config = {
  6. user: 'maxroach',
  7. host: 'localhost',
  8. database: 'bank',
  9. port: 26257,
  10. ssl: {
  11. ca: fs.readFileSync('certs/ca.crt')
  12. .toString(),
  13. key: fs.readFileSync('certs/client.maxroach.key')
  14. .toString(),
  15. cert: fs.readFileSync('certs/client.maxroach.crt')
  16. .toString()
  17. }
  18. };
  19. // Wrapper for a transaction. This automatically re-calls "op" with
  20. // the client as an argument as long as the database server asks for
  21. // the transaction to be retried.
  22. function txnWrapper(client, op, next) {
  23. client.query('BEGIN; SAVEPOINT cockroach_restart', function (err) {
  24. if (err) {
  25. return next(err);
  26. }
  27. var released = false;
  28. async.doWhilst(function (done) {
  29. var handleError = function (err) {
  30. // If we got an error, see if it's a retryable one
  31. // and, if so, restart.
  32. if (err.code === '40001') {
  33. // Signal the database that we'll retry.
  34. return client.query('ROLLBACK TO SAVEPOINT cockroach_restart', done);
  35. }
  36. // A non-retryable error; break out of the
  37. // doWhilst with an error.
  38. return done(err);
  39. };
  40. // Attempt the work.
  41. op(client, function (err) {
  42. if (err) {
  43. return handleError(err);
  44. }
  45. var opResults = arguments;
  46. // If we reach this point, release and commit.
  47. client.query('RELEASE SAVEPOINT cockroach_restart', function (err) {
  48. if (err) {
  49. return handleError(err);
  50. }
  51. released = true;
  52. return done.apply(null, opResults);
  53. });
  54. });
  55. },
  56. function () {
  57. return !released;
  58. },
  59. function (err) {
  60. if (err) {
  61. client.query('ROLLBACK', function () {
  62. next(err);
  63. });
  64. } else {
  65. var txnResults = arguments;
  66. client.query('COMMIT', function (err) {
  67. if (err) {
  68. return next(err);
  69. } else {
  70. return next.apply(null, txnResults);
  71. }
  72. });
  73. }
  74. });
  75. });
  76. }
  77. // The transaction we want to run.
  78. function transferFunds(client, from, to, amount, next) {
  79. // Check the current balance.
  80. client.query('SELECT balance FROM accounts WHERE id = $1', [from], function (err, results) {
  81. if (err) {
  82. return next(err);
  83. } else if (results.rows.length === 0) {
  84. return next(new Error('account not found in table'));
  85. }
  86. var acctBal = results.rows[0].balance;
  87. if (acctBal >= amount) {
  88. // Perform the transfer.
  89. async.waterfall([
  90. function (next) {
  91. // Subtract amount from account 1.
  92. client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from], next);
  93. },
  94. function (updateResult, next) {
  95. // Add amount to account 2.
  96. client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to], next);
  97. },
  98. function (updateResult, next) {
  99. // Fetch account balances after updates.
  100. client.query('SELECT id, balance FROM accounts', function (err, selectResult) {
  101. next(err, selectResult ? selectResult.rows : null);
  102. });
  103. }
  104. ], next);
  105. } else {
  106. next(new Error('insufficient funds'));
  107. }
  108. });
  109. }
  110. // Create a pool.
  111. var pool = new pg.Pool(config);
  112. pool.connect(function (err, client, done) {
  113. // Closes communication with the database and exits.
  114. var finish = function () {
  115. done();
  116. process.exit();
  117. };
  118. if (err) {
  119. console.error('could not connect to cockroachdb', err);
  120. finish();
  121. }
  122. // Execute the transaction.
  123. txnWrapper(client,
  124. function (client, next) {
  125. transferFunds(client, 1, 2, 100, next);
  126. },
  127. function (err, results) {
  128. if (err) {
  129. console.error('error performing transaction', err);
  130. finish();
  131. }
  132. console.log('Balances after transfer:');
  133. results.forEach(function (result) {
  134. console.log(result);
  135. });
  136. finish();
  137. });
  138. });

Then run the code:

  1. $ node txn-sample.js

The output should be:

  1. Balances after transfer:
  2. { id: '1', balance: '900' }
  3. { id: '2', balance: '350' }

To verify that funds were transferred from one account to another, start the built-in SQL client:

  1. $ cockroach sql --certs-dir=certs --database=bank

To check the account balances, issue the following statement:

  1. > SELECT id, balance FROM accounts;
  1. +----+---------+
  2. | id | balance |
  3. +----+---------+
  4. | 1 | 900 |
  5. | 2 | 350 |
  6. +----+---------+
  7. (2 rows)

Step 2. Create the maxroach user and bank database

Start the built-in SQL client:

  1. $ cockroach sql --insecure

In the SQL shell, issue the following statements to create the maxroach user and bank database:

  1. > CREATE USER IF NOT EXISTS maxroach;
  1. > CREATE DATABASE bank;

Give the maxroach user the necessary permissions:

  1. > GRANT ALL ON DATABASE bank TO maxroach;

Exit the SQL shell:

  1. > \q

Step 3. Run the Node.js code

Now that you have a database and a user, you'll run code to create a table and insert some rows, and then you'll run code to read and update values as an atomic transaction.

Basic statements

First, use the following code to connect as the maxroach user and execute some basic SQL statements, creating a table, inserting rows, and reading and printing the rows.

Download the basic-sample.js file, or create the file yourself and copy the code into it.

  1. var async = require('async');
  2. var fs = require('fs');
  3. var pg = require('pg');
  4. // Connect to the "bank" database.
  5. var config = {
  6. user: 'maxroach',
  7. host: 'localhost',
  8. database: 'bank',
  9. port: 26257
  10. };
  11. // Create a pool.
  12. var pool = new pg.Pool(config);
  13. pool.connect(function (err, client, done) {
  14. // Close communication with the database and exit.
  15. var finish = function () {
  16. done();
  17. process.exit();
  18. };
  19. if (err) {
  20. console.error('could not connect to cockroachdb', err);
  21. finish();
  22. }
  23. async.waterfall([
  24. function (next) {
  25. // Create the 'accounts' table.
  26. client.query('CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT);', next);
  27. },
  28. function (results, next) {
  29. // Insert two rows into the 'accounts' table.
  30. client.query('INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250);', next);
  31. },
  32. function (results, next) {
  33. // Print out account balances.
  34. client.query('SELECT id, balance FROM accounts;', next);
  35. },
  36. ],
  37. function (err, results) {
  38. if (err) {
  39. console.error('Error inserting into and selecting from accounts: ', err);
  40. finish();
  41. }
  42. console.log('Initial balances:');
  43. results.rows.forEach(function (row) {
  44. console.log(row);
  45. });
  46. finish();
  47. });
  48. });

Then run the code:

  1. $ node basic-sample.js

The output should be:

  1. Initial balances:
  2. { id: '1', balance: '1000' }
  3. { id: '2', balance: '250' }

Transaction (with retry logic)

Next, use the following code to again connect as the maxroach user but this time execute a batch of statements as an atomic transaction to transfer funds from one account to another and then read the updated values, where all included statements are either committed or aborted.

Download the txn-sample.js file, or create the file yourself and copy the code into it.

Note:

With the default SERIALIZABLE isolation level, CockroachDB may require the client to retry a transaction in case of read/write contention. CockroachDB provides a generic retry function that runs inside a transaction and retries it as needed. The code sample below shows how it is used.

  1. var async = require('async');
  2. var fs = require('fs');
  3. var pg = require('pg');
  4. // Connect to the bank database.
  5. var config = {
  6. user: 'maxroach',
  7. host: 'localhost',
  8. database: 'bank',
  9. port: 26257
  10. };
  11. // Wrapper for a transaction. This automatically re-calls "op" with
  12. // the client as an argument as long as the database server asks for
  13. // the transaction to be retried.
  14. function txnWrapper(client, op, next) {
  15. client.query('BEGIN; SAVEPOINT cockroach_restart', function (err) {
  16. if (err) {
  17. return next(err);
  18. }
  19. var released = false;
  20. async.doWhilst(function (done) {
  21. var handleError = function (err) {
  22. // If we got an error, see if it's a retryable one
  23. // and, if so, restart.
  24. if (err.code === '40001') {
  25. // Signal the database that we'll retry.
  26. return client.query('ROLLBACK TO SAVEPOINT cockroach_restart', done);
  27. }
  28. // A non-retryable error; break out of the
  29. // doWhilst with an error.
  30. return done(err);
  31. };
  32. // Attempt the work.
  33. op(client, function (err) {
  34. if (err) {
  35. return handleError(err);
  36. }
  37. var opResults = arguments;
  38. // If we reach this point, release and commit.
  39. client.query('RELEASE SAVEPOINT cockroach_restart', function (err) {
  40. if (err) {
  41. return handleError(err);
  42. }
  43. released = true;
  44. return done.apply(null, opResults);
  45. });
  46. });
  47. },
  48. function () {
  49. return !released;
  50. },
  51. function (err) {
  52. if (err) {
  53. client.query('ROLLBACK', function () {
  54. next(err);
  55. });
  56. } else {
  57. var txnResults = arguments;
  58. client.query('COMMIT', function (err) {
  59. if (err) {
  60. return next(err);
  61. } else {
  62. return next.apply(null, txnResults);
  63. }
  64. });
  65. }
  66. });
  67. });
  68. }
  69. // The transaction we want to run.
  70. function transferFunds(client, from, to, amount, next) {
  71. // Check the current balance.
  72. client.query('SELECT balance FROM accounts WHERE id = $1', [from], function (err, results) {
  73. if (err) {
  74. return next(err);
  75. } else if (results.rows.length === 0) {
  76. return next(new Error('account not found in table'));
  77. }
  78. var acctBal = results.rows[0].balance;
  79. if (acctBal >= amount) {
  80. // Perform the transfer.
  81. async.waterfall([
  82. function (next) {
  83. // Subtract amount from account 1.
  84. client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from], next);
  85. },
  86. function (updateResult, next) {
  87. // Add amount to account 2.
  88. client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to], next);
  89. },
  90. function (updateResult, next) {
  91. // Fetch account balances after updates.
  92. client.query('SELECT id, balance FROM accounts', function (err, selectResult) {
  93. next(err, selectResult ? selectResult.rows : null);
  94. });
  95. }
  96. ], next);
  97. } else {
  98. next(new Error('insufficient funds'));
  99. }
  100. });
  101. }
  102. // Create a pool.
  103. var pool = new pg.Pool(config);
  104. pool.connect(function (err, client, done) {
  105. // Closes communication with the database and exits.
  106. var finish = function () {
  107. done();
  108. process.exit();
  109. };
  110. if (err) {
  111. console.error('could not connect to cockroachdb', err);
  112. finish();
  113. }
  114. // Execute the transaction.
  115. txnWrapper(client,
  116. function (client, next) {
  117. transferFunds(client, 1, 2, 100, next);
  118. },
  119. function (err, results) {
  120. if (err) {
  121. console.error('error performing transaction', err);
  122. finish();
  123. }
  124. console.log('Balances after transfer:');
  125. results.forEach(function (result) {
  126. console.log(result);
  127. });
  128. finish();
  129. });
  130. });

Then run the code:

  1. $ node txn-sample.js

The output should be:

  1. Balances after transfer:
  2. { id: '1', balance: '900' }
  3. { id: '2', balance: '350' }

To verify that funds were transferred from one account to another, start the built-in SQL client:

  1. $ cockroach sql --insecure --database=bank

To check the account balances, issue the following statement:

  1. > SELECT id, balance FROM accounts;
  1. +----+---------+
  2. | id | balance |
  3. +----+---------+
  4. | 1 | 900 |
  5. | 2 | 350 |
  6. +----+---------+
  7. (2 rows)

What's next?

Read more about using the Node.js pg driver.

You might also be interested in using a local cluster to explore the following CockroachDB benefits:

Was this page helpful?
YesNo