-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtxn_example.py
185 lines (149 loc) · 7.19 KB
/
txn_example.py
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# Copyright 2022 PingCAP, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import MySQLdb
import os
import datetime
from threading import Thread
REPEATABLE_ERROR_CODE_SET = {
9007, # Transactions in TiKV encounter write conflicts.
8028, # table schema changes
8002, # "SELECT FOR UPDATE" commit conflict
8022 # The transaction commit fails and has been rolled back
}
def create_connection():
return MySQLdb.connect(
host="127.0.0.1",
port=4000,
user="root",
password="",
database="bookshop",
autocommit=False
)
def prepare_data() -> None:
connection = create_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute("INSERT INTO `books` (`id`, `title`, `type`, `published_at`, `price`, `stock`) "
"values (%s, %s, %s, %s, %s, %s)",
(1, "Designing Data-Intensive Application", "Science & Technology",
datetime.datetime(2018, 9, 1), 100, 10))
cursor.executemany("INSERT INTO `users` (`id`, `nickname`, `balance`) VALUES (%s, %s, %s)",
[(1, "Bob", 10000), (2, "ALICE", 10000)])
connection.commit()
def buy_optimistic(thread_id: int, order_id: int, book_id: int, user_id: int, amount: int,
optimistic_retry_times: int = 5) -> None:
connection = create_connection()
txn_log_header = f"/* txn {thread_id} */"
if thread_id != 1:
txn_log_header = "\t" + txn_log_header
with connection:
with connection.cursor() as cursor:
cursor.execute("BEGIN OPTIMISTIC")
print(f'{txn_log_header} BEGIN OPTIMISTIC')
time.sleep(1)
try:
# read the price of book
select_book_for_update = "SELECT `price`, `stock` FROM books WHERE id = %s FOR UPDATE"
cursor.execute(select_book_for_update, (book_id,))
book = cursor.fetchone()
if book is None:
raise Exception("book_id not exist")
price, stock = book
print(f'{txn_log_header} {select_book_for_update} successful')
if stock < amount:
raise Exception("book not enough, rollback")
# update book
update_stock = "update `books` set stock = stock - %s where id = %s and stock - %s >= 0"
rows_affected = cursor.execute(update_stock, (amount, book_id, amount))
print(f'{txn_log_header} {update_stock} successful')
if rows_affected == 0:
raise Exception("stock not enough, rollback")
# insert order
insert_order = "insert into `orders` (`id`, `book_id`, `user_id`, `quality`) values (%s, %s, %s, %s)"
cursor.execute(insert_order, (order_id, book_id, user_id, amount))
print(f'{txn_log_header} {insert_order} successful')
# update user
update_user = "update `users` set `balance` = `balance` - %s where id = %s"
cursor.execute(update_user, (amount * price, user_id))
print(f'{txn_log_header} {update_user} successful')
except Exception as err:
connection.rollback()
print(f'something went wrong: {err}')
else:
# important here! you need deal the Exception from the TiDB
try:
connection.commit()
except MySQLdb.MySQLError as db_err:
code, desc = db_err.args
if code in REPEATABLE_ERROR_CODE_SET and optimistic_retry_times > 0:
print(f'retry, rest {optimistic_retry_times - 1} times, for {code} {desc}')
buy_optimistic(thread_id, order_id, book_id, user_id, amount, optimistic_retry_times - 1)
def buy_pessimistic(thread_id: int, order_id: int, book_id: int, user_id: int, amount: int) -> None:
connection = create_connection()
txn_log_header = f"/* txn {thread_id} */"
if thread_id != 1:
txn_log_header = "\t" + txn_log_header
with connection:
with connection.cursor() as cursor:
cursor.execute("BEGIN PESSIMISTIC")
print(f'{txn_log_header} BEGIN PESSIMISTIC')
time.sleep(1)
try:
# read the price of book
select_book_for_update = "SELECT `price` FROM books WHERE id = %s FOR UPDATE"
cursor.execute(select_book_for_update, (book_id,))
book = cursor.fetchone()
if book is None:
raise Exception("book_id not exist")
price = book[0]
print(f'{txn_log_header} {select_book_for_update} successful')
# update book
update_stock = "update `books` set stock = stock - %s where id = %s and stock - %s >= 0"
rows_affected = cursor.execute(update_stock, (amount, book_id, amount))
print(f'{txn_log_header} {update_stock} successful')
if rows_affected == 0:
raise Exception("stock not enough, rollback")
# insert order
insert_order = "insert into `orders` (`id`, `book_id`, `user_id`, `quality`) values (%s, %s, %s, %s)"
cursor.execute(insert_order, (order_id, book_id, user_id, amount))
print(f'{txn_log_header} {insert_order} successful')
# update user
update_user = "update `users` set `balance` = `balance` - %s where id = %s"
cursor.execute(update_user, (amount * price, user_id))
print(f'{txn_log_header} {update_user} successful')
except Exception as err:
connection.rollback()
print(f'something went wrong: {err}')
else:
connection.commit()
optimistic = os.environ.get('OPTIMISTIC')
alice = os.environ.get('ALICE')
bob = os.environ.get('BOB')
if not (optimistic and alice and bob):
raise Exception("please use \"OPTIMISTIC=<is_optimistic> ALICE=<alice_num> "
"BOB=<bob_num> python3 txn_example.py\" to start this script")
prepare_data()
if not bool(optimistic):
buy_func = buy_optimistic
else:
buy_func = buy_pessimistic
bob_thread = Thread(target=buy_func, kwargs={
"thread_id": 1, "order_id": 1000, "book_id": 1, "user_id": 1, "amount": int(bob)})
alice_thread = Thread(target=buy_func, kwargs={
"thread_id": 2, "order_id": 1001, "book_id": 1, "user_id": 2, "amount": int(alice)})
bob_thread.start()
alice_thread.start()
bob_thread.join(timeout=10)
alice_thread.join(timeout=10)