Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions _includes/app/TxnSample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
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 {}
class AccountNotFoundException extends Exception {
public int account;
public AccountNotFoundException(int account) {
this.account = account;
}
}

// A simple interface that provides a retryable lambda expression.
interface RetryableTransaction {
public void run(Connection conn)
throws SQLException, InsufficientBalanceException, AccountNotFoundException;
}

public class TxnSample {
public static RetryableTransaction transferFunds(int from, int to, int amount) {
return new RetryableTransaction() {
public void run(Connection conn)
throws SQLException, InsufficientBalanceException, AccountNotFoundException {
// Check the current balance.
ResultSet res = conn.createStatement().executeQuery("SELECT balance FROM accounts WHERE id = " + from);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add comment before line 20: # Check the current balance.

if(!res.next()) {
throw new AccountNotFoundException(from);
}
int balance = res.getInt("balance");
if(balance < from) {
throw new InsufficientBalanceException();
}
// Perform the transfer.
conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance - " + amount + " where id = " + from);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add comment before line 28: # Perform the transfer.

conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance + " + amount + " where id = " + to);
}
};
}

public static void retryTransaction(Connection conn, RetryableTransaction tx)
throws SQLException, InsufficientBalanceException, AccountNotFoundException {
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);
// Perform the transfer. This assumes the table has
// already been set up as in the "Build a Test App"
// tutorial.
RetryableTransaction transfer = transferFunds(1, 2, 100);
retryTransaction(db, transfer);
// Check balances after transfer.
ResultSet res = db.createStatement().executeQuery("SELECT id, balance FROM accounts");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add comment before line 70: # Check balances after transfer.

while (res.next()) {
System.out.printf("\taccount %s: %s\n", res.getInt("id"), res.getInt("balance"));
}
} catch(InsufficientBalanceException e) {
System.out.println("Insufficient balance");
} catch(AccountNotFoundException e) {
System.out.println("No users in the table with id " + e.account);
} catch(SQLException e) {
System.out.println("SQLException encountered:" + e);
} finally {
// Close the database connection.
db.close();
}
}
}
Empty file removed _includes/app/txn-sample.java
Empty file.
23 changes: 12 additions & 11 deletions build-a-test-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<asciinema-player class="asciinema-demo" src="asciicasts/build-a-test-app.json" cols="107" speed="2" theme="monokai" poster="npt:0:40" title="Build a Test App"></asciinema-player>

## 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`.
Expand Down Expand Up @@ -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)'
~~~

~~~
Expand Down Expand Up @@ -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 <strong>retry function</strong> 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 <a href="https://www.cockroachlabs.com/docs/transactions.html#transaction-retries">Transaction Retries</a>.{{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 <strong>retry function</strong> 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 <a href="https://www.cockroachlabs.com/docs/transactions.html#transaction-retries">Transaction Retries</a>.{{site.data.alerts.end}}

<div id="step-four-filters" class="filters clearfix">
<button class="filter-button current" data-language="python">Python</button>
Expand Down Expand Up @@ -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
~~~

Expand All @@ -213,7 +213,9 @@ $ git clone git@github.com:cockroachdb/cockroach-go.git
<div class="filter-content" markdown="1" data-language="java">
**Java**

Coming soon.
~~~ java
{% include app/TxnSample.java %}
~~~
</div>

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to put the closing </div> back in. Otherwise, the other transaction samples don't show up.

<div class="filter-content" markdown="1" data-language="nodejs">
Expand Down Expand Up @@ -267,11 +269,11 @@ Use a local cluster to explore the following core CockroachDB features:

<script>
$(document).ready(function(){

var $filter_button = $('.filter-button');

$filter_button.on('click', function(){
var language = $(this).data('language'),
var language = $(this).data('language'),
$current_tab = $('.filter-button.current'), $current_content = $('.filter-content.current');

//remove current class from tab and content
Expand All @@ -284,4 +286,3 @@ $(document).ready(function(){
});
});
</script>