Skip to content

Commit 78401de

Browse files
committed
Clean up versioning of includes
Fixes cockroachdb#3265
1 parent d650124 commit 78401de

File tree

1,347 files changed

+11777
-1306
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

1,347 files changed

+11777
-1306
lines changed

CONTRIBUTING.md

+1-1
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

_includes/faq/sql-query-logging.md renamed to _includes/v1.0/faq/sql-query-logging.md

+1-1

_includes/v1.1/app/BasicSample.java

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.sql.*;
2+
3+
/*
4+
You can compile and run this example with a command like:
5+
javac BasicSample.java && java -cp .:~/path/to/postgresql-9.4.1208.jar BasicSample
6+
You can download the postgres JDBC driver jar from https://jdbc.postgresql.org.
7+
*/
8+
public class BasicSample {
9+
public static void main(String[] args) throws ClassNotFoundException, SQLException {
10+
// Load the postgres JDBC driver.
11+
Class.forName("org.postgresql.Driver");
12+
13+
// Connect to the "bank" database.
14+
Connection db = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:26257/bank?sslmode=disable", "maxroach", "");
15+
16+
try {
17+
// Create the "accounts" table.
18+
db.createStatement().execute("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)");
19+
20+
// Insert two rows into the "accounts" table.
21+
db.createStatement().execute("INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)");
22+
23+
// Print out the balances.
24+
System.out.println("Initial balances:");
25+
ResultSet res = db.createStatement().executeQuery("SELECT id, balance FROM accounts");
26+
while (res.next()) {
27+
System.out.printf("\taccount %s: %s\n", res.getInt("id"), res.getInt("balance"));
28+
}
29+
} finally {
30+
// Close the database connection.
31+
db.close();
32+
}
33+
}
34+
}

_includes/v1.1/app/TxnSample.java

+113
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import java.sql.*;
2+
3+
/*
4+
You can compile and run this example with a command like:
5+
javac TxnSample.java && java -cp .:~/path/to/postgresql-9.4.1208.jar TxnSample
6+
You can download the postgres JDBC driver jar from https://jdbc.postgresql.org.
7+
*/
8+
9+
// Ambiguous whether the transaction committed or not.
10+
class AmbiguousCommitException extends SQLException{
11+
public AmbiguousCommitException(Throwable cause) {
12+
super(cause);
13+
}
14+
}
15+
class InsufficientBalanceException extends Exception {}
16+
class AccountNotFoundException extends Exception {
17+
public int account;
18+
public AccountNotFoundException(int account) {
19+
this.account = account;
20+
}
21+
}
22+
23+
// A simple interface that provides a retryable lambda expression.
24+
interface RetryableTransaction {
25+
public void run(Connection conn)
26+
throws SQLException, InsufficientBalanceException, AccountNotFoundException, AmbiguousCommitException;
27+
}
28+
29+
public class TxnSample {
30+
public static RetryableTransaction transferFunds(int from, int to, int amount) {
31+
return new RetryableTransaction() {
32+
public void run(Connection conn)
33+
throws SQLException, InsufficientBalanceException, AccountNotFoundException, AmbiguousCommitException {
34+
// Check the current balance.
35+
ResultSet res = conn.createStatement().executeQuery("SELECT balance FROM accounts WHERE id = " + from);
36+
if(!res.next()) {
37+
throw new AccountNotFoundException(from);
38+
}
39+
int balance = res.getInt("balance");
40+
if(balance < from) {
41+
throw new InsufficientBalanceException();
42+
}
43+
// Perform the transfer.
44+
conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance - " + amount + " where id = " + from);
45+
conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance + " + amount + " where id = " + to);
46+
}
47+
};
48+
}
49+
50+
public static void retryTransaction(Connection conn, RetryableTransaction tx)
51+
throws SQLException, InsufficientBalanceException, AccountNotFoundException, AmbiguousCommitException {
52+
Savepoint sp = conn.setSavepoint("cockroach_restart");
53+
while(true) {
54+
boolean releaseAttempted = false;
55+
try {
56+
tx.run(conn);
57+
releaseAttempted = true;
58+
conn.releaseSavepoint(sp);
59+
}
60+
catch(SQLException e) {
61+
String sqlState = e.getSQLState();
62+
// Check if the error code indicates a SERIALIZATION_FAILURE.
63+
if(sqlState.equals("40001")) {
64+
// Signal the database that we will attempt a retry.
65+
conn.rollback(sp);
66+
continue;
67+
} else if(releaseAttempted) {
68+
throw new AmbiguousCommitException(e);
69+
} else {
70+
throw e;
71+
}
72+
}
73+
break;
74+
}
75+
conn.commit();
76+
}
77+
78+
public static void main(String[] args) throws ClassNotFoundException, SQLException {
79+
// Load the postgres JDBC driver.
80+
Class.forName("org.postgresql.Driver");
81+
82+
// Connect to the "bank" database.
83+
Connection db = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:26257/bank?sslmode=disable", "maxroach", "");
84+
try {
85+
// We need to turn off autocommit mode to allow for
86+
// multi-statement transactions.
87+
db.setAutoCommit(false);
88+
// Perform the transfer. This assumes the table has
89+
// already been set up as in the "Build a Test App"
90+
// tutorial.
91+
RetryableTransaction transfer = transferFunds(1, 2, 100);
92+
retryTransaction(db, transfer);
93+
94+
// Check balances after transfer.
95+
db.setAutoCommit(true);
96+
ResultSet res = db.createStatement().executeQuery("SELECT id, balance FROM accounts");
97+
while (res.next()) {
98+
System.out.printf("\taccount %s: %s\n", res.getInt("id"), res.getInt("balance"));
99+
}
100+
} catch(InsufficientBalanceException e) {
101+
System.out.println("Insufficient balance");
102+
} catch(AccountNotFoundException e) {
103+
System.out.println("No users in the table with id " + e.account);
104+
} catch(AmbiguousCommitException e) {
105+
System.out.println("Ambiguous result encountered: " + e);
106+
} catch(SQLException e) {
107+
System.out.println("SQLException encountered:" + e);
108+
} finally {
109+
// Close the database connection.
110+
db.close();
111+
}
112+
}
113+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
require 'active_record'
2+
require 'pg'
3+
require 'activerecord-cockroachdb-adapter'
4+
5+
# Connect to CockroachDB through ActiveRecord.
6+
# In Rails, this configuration would go in config/database.yml as usual.
7+
ActiveRecord::Base.establish_connection(
8+
adapter: 'cockroachdb',
9+
username: 'maxroach',
10+
password: '',
11+
database: 'bank',
12+
host: 'localhost',
13+
port: 26257,
14+
)
15+
16+
17+
# Define the Account model.
18+
# In Rails, this would go in app/models/ as usual.
19+
class Account < ActiveRecord::Base
20+
validates :id, presence: true
21+
validates :balance, presence: true
22+
end
23+
24+
# Define a migration for the accounts table.
25+
# In Rails, this would go in db/migrate/ as usual.
26+
class Schema < ActiveRecord::Migration
27+
def change
28+
create_table :accounts, force: true do |t|
29+
t.integer :balance
30+
end
31+
end
32+
end
33+
34+
# Run the schema migration by hand.
35+
# In Rails, this would be done via rake db:migrate as usual.
36+
Schema.new.change()
37+
38+
# Create two accounts, inserting two rows into the accounts table.
39+
Account.create(id: 1, balance: 1000)
40+
Account.create(id: 2, balance: 250)
41+
42+
# Retrieve accounts and print out the balances
43+
Account.all.each do |acct|
44+
puts "#{acct.id} #{acct.balance}"
45+
end

_includes/v1.1/app/basic-sample.clj

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
(ns test.test
2+
(:require [clojure.java.jdbc :as j]
3+
[test.util :as util]))
4+
5+
;; Define the connection parameters to the cluster.
6+
(def db-spec {:subprotocol "postgresql"
7+
:subname "//localhost:26257/bank"
8+
:user "maxroach"
9+
:password ""})
10+
11+
(defn test-basic []
12+
;; Connect to the cluster and run the code below with
13+
;; the connection object bound to 'conn'.
14+
(j/with-db-connection [conn db-spec]
15+
16+
;; Insert two rows into the "accounts" table.
17+
(j/insert! conn :accounts {:id 1 :balance 1000})
18+
(j/insert! conn :accounts {:id 2 :balance 250})
19+
20+
;; Print out the balances.
21+
(println "Initial balances:")
22+
(->> (j/query conn ["SELECT id, balance FROM accounts"])
23+
(map println)
24+
doall)
25+
26+
;; The database connection is automatically closed by with-db-connection.
27+
))
28+
29+
30+
(defn -main [& args]
31+
(test-basic))

_includes/v1.1/app/basic-sample.cpp

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Build with g++ -std=c++11 basic-sample.cpp -lpq -lpqxx
2+
3+
#include <cassert>
4+
#include <functional>
5+
#include <iostream>
6+
#include <stdexcept>
7+
#include <string>
8+
#include <pqxx/pqxx>
9+
10+
using namespace std;
11+
12+
int main() {
13+
try {
14+
// Connect to the "bank" database.
15+
pqxx::connection c("postgresql://maxroach@localhost:26257/bank");
16+
17+
pqxx::nontransaction w(c);
18+
19+
// Create the "accounts" table.
20+
w.exec("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)");
21+
22+
// Insert two rows into the "accounts" table.
23+
w.exec("INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)");
24+
25+
// Print out the balances.
26+
cout << "Initial balances:" << endl;
27+
pqxx::result r = w.exec("SELECT id, balance FROM accounts");
28+
for (auto row : r) {
29+
cout << row[0].as<int>() << ' ' << row[1].as<int>() << endl;
30+
}
31+
32+
w.commit(); // Note this doesn't doesn't do anything
33+
// for a nontransaction, but is still required.
34+
}
35+
catch (const exception &e) {
36+
cerr << e.what() << endl;
37+
return 1;
38+
}
39+
cout << "Success" << endl;
40+
return 0;
41+
}

_includes/v1.1/app/basic-sample.cs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
using System;
2+
using System.Data;
3+
using Npgsql;
4+
5+
namespace Cockroach
6+
{
7+
class MainClass
8+
{
9+
static void Main(string[] args)
10+
{
11+
var connStringBuilder = new NpgsqlConnectionStringBuilder();
12+
connStringBuilder.Host = "localhost";
13+
connStringBuilder.Port = 26257;
14+
connStringBuilder.Username = "maxroach";
15+
connStringBuilder.Database = "bank";
16+
Simple(connStringBuilder.ConnectionString);
17+
}
18+
19+
static void Simple(string connString)
20+
{
21+
using(var conn = new NpgsqlConnection(connString))
22+
{
23+
conn.Open();
24+
25+
// Create the "accounts" table.
26+
new NpgsqlCommand("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)", conn).ExecuteNonQuery();
27+
28+
// Insert two rows into the "accounts" table.
29+
using(var cmd = new NpgsqlCommand())
30+
{
31+
cmd.Connection = conn;
32+
cmd.CommandText = "UPSERT INTO accounts(id, balance) VALUES(@id1, @val1), (@id2, @val2)";
33+
cmd.Parameters.AddWithValue("id1", 1);
34+
cmd.Parameters.AddWithValue("val1", 1000);
35+
cmd.Parameters.AddWithValue("id2", 2);
36+
cmd.Parameters.AddWithValue("val2", 250);
37+
cmd.ExecuteNonQuery();
38+
}
39+
40+
// Print out the balances.
41+
System.Console.WriteLine("Initial balances:");
42+
using(var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn))
43+
using(var reader = cmd.ExecuteReader())
44+
while (reader.Read())
45+
Console.Write("\taccount {0}: {1}\n", reader.GetString(0), reader.GetString(1));
46+
}
47+
}
48+
}
49+
}

_includes/v1.1/app/basic-sample.go

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package main
2+
3+
import (
4+
"database/sql"
5+
"fmt"
6+
"log"
7+
8+
_ "github.com/lib/pq"
9+
)
10+
11+
func main() {
12+
// Connect to the "bank" database.
13+
db, err := sql.Open("postgres", "postgresql://maxroach@localhost:26257/bank?sslmode=disable")
14+
if err != nil {
15+
log.Fatal("error connecting to the database: ", err)
16+
}
17+
18+
// Create the "accounts" table.
19+
if _, err := db.Exec(
20+
"CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)"); err != nil {
21+
log.Fatal(err)
22+
}
23+
24+
// Insert two rows into the "accounts" table.
25+
if _, err := db.Exec(
26+
"INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)"); err != nil {
27+
log.Fatal(err)
28+
}
29+
30+
// Print out the balances.
31+
rows, err := db.Query("SELECT id, balance FROM accounts")
32+
if err != nil {
33+
log.Fatal(err)
34+
}
35+
defer rows.Close()
36+
fmt.Println("Initial balances:")
37+
for rows.Next() {
38+
var id, balance int
39+
if err := rows.Scan(&id, &balance); err != nil {
40+
log.Fatal(err)
41+
}
42+
fmt.Printf("%d %d\n", id, balance)
43+
}
44+
}

0 commit comments

Comments
 (0)