From 3e91e90aa95f1b86d83cd446073764e22e8b8ba9 Mon Sep 17 00:00:00 2001 From: Arjun Narayan Date: Wed, 11 Jan 2017 17:08:28 -0500 Subject: [PATCH] Test App: Add Java code for transaction retries Add example code for transaction retry logic. Compilation and execution instructions are in a comment in the main code file. Fixes #757. --- _includes/app/TxnSample.java | 83 +++++++++++++++++++++++++++++++++++ _includes/app/txn-sample.java | 0 build-a-test-app.md | 24 +++++----- 3 files changed, 95 insertions(+), 12 deletions(-) create mode 100644 _includes/app/TxnSample.java delete mode 100644 _includes/app/txn-sample.java diff --git a/_includes/app/TxnSample.java b/_includes/app/TxnSample.java new file mode 100644 index 00000000000..d799d7e493e --- /dev/null +++ b/_includes/app/TxnSample.java @@ -0,0 +1,83 @@ +import java.sql.*; + +/* + You can compile and run this example with a command like: + javac TxnSample.java && java -cp .:~/path/to/postgresql-9.4.1208.jar TxnSample + You can download the postgres JDBC driver jar from https://jdbc.postgresql.org. +*/ + +class InsufficientBalanceException extends Exception {} + +// A simple interface that provides a retryable lambda expression. +interface RetryableTransaction { + public void run(Connection conn) throws Exception; +} + +public class TxnSample { + public static RetryableTransaction transferFunds(int from, int to, int amount) { + return new RetryableTransaction() { + public void run(Connection conn) throws Exception { + ResultSet res = conn.createStatement().executeQuery("SELECT balance FROM accounts WHERE id = " + from); + res.next(); + int balance = res.getInt("balance"); + if(balance < from) { + throw new InsufficientBalanceException(); + } + conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance - " + amount + " where id = " + from); + conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance + " + amount + " where id = " + to); + } + }; + } + + public static void retryTransaction(Connection conn, RetryableTransaction tx) throws Exception { + Savepoint sp = conn.setSavepoint("cockroach_restart"); + while(true) { + try { + // Attempt the transaction. + tx.run(conn); + + // If we reach this point, commit the transaction, + // which implicitly releases the savepoint. + conn.commit(); + break; + } catch(SQLException e) { + // Check if the error code indicates a SERIALIZATION_FAILURE. + if(e.getErrorCode() == 40001) { + // Signal the database that we will attempt a retry. + conn.rollback(sp); + } + // This is a not a serialization failure, pass it up the chain. + throw e; + } + } + } + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + // Load the postgres JDBC driver. + Class.forName("org.postgresql.Driver"); + + // Connect to the "bank" database. + Connection db = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:26257/bank?sslmode=disable", "maxroach", ""); + try { + // We need to turn off autocommit mode to allow for + // multi-statement transactions. + db.setAutoCommit(false); + + RetryableTransaction transfer = transferFunds(1, 2, 100); + retryTransaction(db, transfer); + ResultSet res = db.createStatement().executeQuery("SELECT id, balance FROM accounts"); + while (res.next()) { + System.out.printf("\taccount %s: %s\n", res.getInt("id"), res.getInt("balance")); + } + } catch(InsufficientBalanceException ibe) { + System.out.println("Insufficient balance"); + } catch(SQLException sqle) { + System.out.println("SQLException encountered:" + sqle); + } catch(Exception e) { + System.out.println("Unknown exception encountered:" + e); + } finally { + // Close the database connection. + db.close(); + } + } +} diff --git a/_includes/app/txn-sample.java b/_includes/app/txn-sample.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/build-a-test-app.md b/build-a-test-app.md index a8b3be2974a..f577b5b5d37 100644 --- a/build-a-test-app.md +++ b/build-a-test-app.md @@ -13,14 +13,14 @@ This page is CockroachDB's **Hello, World!** tutorial. It walks you through crea Make sure you have already: -- [Installed CockroachDB](install-cockroachdb.html) +- [Installed CockroachDB](install-cockroachdb.html) - [Started a local cluster](start-a-local-cluster.html) in insecure mode - [Installed a client driver](install-client-drivers.html) Feel free to watch this process in action before going through the steps yourself. Note that the demo video features Python code for executing basic statements (step 4), but the code for executing more complex transactions is not covered (step 5). Also note that you can copy commands directly from the video, and you can use **<** and **>** to go back and forward. - + ## Step 1. Create a user As the `root` user, use the [`cockroach user`](create-and-manage-users.html) command to create a new user, `maxroach`. @@ -59,7 +59,7 @@ As the `maxroach` user, use the [built-in SQL client](use-the-built-in-sql-clien ~~~ shell $ cockroach sql --database=bank --user=maxroach -e \ -'CREATE TABLE accounts (id INT PRIMARY KEY, balance INT)' +'CREATE TABLE accounts (id INT PRIMARY KEY, balance INT)' ~~~ ~~~ @@ -164,9 +164,9 @@ Initial balances: ## Step 5. Execute transactions from a client -As the `maxroach` user, connect again from your preferred language, but this time execute a batch of statements as an atomic transaction, where all included statements are either commited or aborted. +As the `maxroach` user, connect again from your preferred language, but this time execute a batch of statements as an atomic transaction, where all included statements are either commited or aborted. -{{site.data.alerts.callout_info}}Because the CockroachDB transaction model requires the client to initiate retries in the case of contention, CockroachDB provides a generic retry function that runs inside a transaction and retries it as needed. You can copy and paste the retry function from here into your code. For more details, see Transaction Retries.{{site.data.alerts.end}} +{{site.data.alerts.callout_info}}Because the CockroachDB transaction model requires the client to initiate retries in the case of contention, CockroachDB provides a generic retry function that runs inside a transaction and retries it as needed. You can copy and paste the retry function from here into your code. For more details, see Transaction Retries.{{site.data.alerts.end}}
@@ -200,8 +200,8 @@ Coming soon. For Go, the CockroachDB retry function is in the `crdb` package of the CockroachDB Go client. You can clone the library into your `$GOPATH` as follows: ~~~ shell -$ mkdir -p $GOPATH/github.com/cockroachdb -$ cd $GOPATH/github.com/cockroachdb +$ mkdir -p $GOPATH/github.com/cockroachdb +$ cd $GOPATH/github.com/cockroachdb $ git clone git@github.com:cockroachdb/cockroach-go.git ~~~ @@ -213,8 +213,9 @@ $ git clone git@github.com:cockroachdb/cockroach-go.git
**Java** -Coming soon. -
+~~~ java +{% include app/TxnSample.java %} +~~~
**Node.js** @@ -267,11 +268,11 @@ Use a local cluster to explore the following core CockroachDB features: -