-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsample-app.php
93 lines (68 loc) · 2.64 KB
/
sample-app.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
define('HOST', '127.0.0.1');
define('PORT', '5433');
define('DB_NAME', 'yugabyte');
define('USER', 'yugabyte');
define('PASSWORD', 'yugabyte');
define('SSL_MODE', 'disable');
define('SSL_ROOT_CERT', '');
function connect() {
print ">>>> Connecting to YugabyteDB!\n";
$conn_str = 'pgsql:host=' . HOST . ';port=' . PORT . ';dbname=' . DB_NAME .
';sslmode=' . SSL_MODE;
if (SSL_ROOT_CERT !== '') {
$conn_str = $conn_str . ';sslrootcert=' . SSL_ROOT_CERT;
}
$conn = new PDO($conn_str,
USER, PASSWORD,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => true,
PDO::ATTR_PERSISTENT => true));
print ">>>> Successfully connected to YugabyteDB!\n";
return $conn;
}
function create_database(&$conn) {
$conn->exec('DROP TABLE IF EXISTS DemoAccount');
$conn->exec('CREATE TABLE DemoAccount (
id int PRIMARY KEY,
name varchar,
age int,
country varchar,
balance int)');
$conn->exec("INSERT INTO DemoAccount VALUES
(1, 'Jessica', 28, 'USA', 10000),
(2, 'John', 28, 'Canada', 9000)");
print ">>>> Successfully created table DemoAccount.\n";
}
function select_accounts(&$conn) {
print ">>>> Selecting accounts:\n";
$query = 'SELECT name, age, country, balance FROM DemoAccount';
foreach ($conn->query($query) as $row) {
print 'name=' . $row['name'] . ', age=' . $row['age'] . ', country=' . $row['country'] . ', balance=' . $row['balance'] . "\n";
}
}
function transfer_money_between_accounts(&$conn, $amount) {
try {
$conn->beginTransaction();
$conn->exec("UPDATE DemoAccount SET balance = balance - " . $amount . " WHERE name = 'Jessica'");
$conn->exec("UPDATE DemoAccount SET balance = balance + " . $amount . " WHERE name = 'John'");
$conn->commit();
print ">>>> Transferred " . $amount . " between accounts\n";
} catch (PDOException $e) {
if ($e->getCode() == '40001') {
print "The operation is aborted due to a concurrent transaction that is modifying the same set of rows.
Consider adding retry logic or using the pessimistic locking.\n";
}
throw $e;
}
}
try {
$conn = connect();
create_database($conn);
select_accounts($conn);
transfer_money_between_accounts($conn, 800);
select_accounts($conn);
} catch (Exception $excp) {
print "EXCEPTION: " . $excp->getMessage() . "\n";
exit(1);
}