-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmongodbdriver.py
1175 lines (1049 loc) · 49.9 KB
/
mongodbdriver.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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------
# Copyright (C) 2011
# Andy Pavlo
# http://www.cs.brown.edu/~pavlo/
#
# Original Java Version:
# Copyright (C) 2008
# Evan Jones
# Massachusetts Institute of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# -----------------------------------------------------------------------
from __future__ import with_statement
import sys
import json
import logging
import urllib
from pprint import pformat
from time import sleep
import pymongo
import constants
from abstractdriver import AbstractDriver
TABLE_COLUMNS = {
constants.TABLENAME_ITEM: [
"I_ID", # INTEGER
"I_IM_ID", # INTEGER
"I_NAME", # VARCHAR
"I_PRICE", # FLOAT
"I_DATA", # VARCHAR
"I_W_ID", # INTEGER
],
constants.TABLENAME_WAREHOUSE: [
"W_ID", # SMALLINT
"W_NAME", # VARCHAR
"W_STREET_1", # VARCHAR
"W_STREET_2", # VARCHAR
"W_CITY", # VARCHAR
"W_STATE", # VARCHAR
"W_ZIP", # VARCHAR
"W_TAX", # FLOAT
"W_YTD", # FLOAT
],
constants.TABLENAME_DISTRICT: [
"D_ID", # TINYINT
"D_W_ID", # SMALLINT
"D_NAME", # VARCHAR
"D_STREET_1", # VARCHAR
"D_STREET_2", # VARCHAR
"D_CITY", # VARCHAR
"D_STATE", # VARCHAR
"D_ZIP", # VARCHAR
"D_TAX", # FLOAT
"D_YTD", # FLOAT
"D_NEXT_O_ID", # INT
],
constants.TABLENAME_CUSTOMER: [
"C_ID", # INTEGER
"C_D_ID", # TINYINT
"C_W_ID", # SMALLINT
"C_FIRST", # VARCHAR
"C_MIDDLE", # VARCHAR
"C_LAST", # VARCHAR
"C_STREET_1", # VARCHAR
"C_STREET_2", # VARCHAR
"C_CITY", # VARCHAR
"C_STATE", # VARCHAR
"C_ZIP", # VARCHAR
"C_PHONE", # VARCHAR
"C_SINCE", # TIMESTAMP
"C_CREDIT", # VARCHAR
"C_CREDIT_LIM", # FLOAT
"C_DISCOUNT", # FLOAT
"C_BALANCE", # FLOAT
"C_YTD_PAYMENT", # FLOAT
"C_PAYMENT_CNT", # INTEGER
"C_DELIVERY_CNT", # INTEGER
"C_DATA", # VARCHAR
],
constants.TABLENAME_STOCK: [
"S_I_ID", # INTEGER
"S_W_ID", # SMALLINT
"S_QUANTITY", # INTEGER
"S_DIST_01", # VARCHAR
"S_DIST_02", # VARCHAR
"S_DIST_03", # VARCHAR
"S_DIST_04", # VARCHAR
"S_DIST_05", # VARCHAR
"S_DIST_06", # VARCHAR
"S_DIST_07", # VARCHAR
"S_DIST_08", # VARCHAR
"S_DIST_09", # VARCHAR
"S_DIST_10", # VARCHAR
"S_YTD", # INTEGER
"S_ORDER_CNT", # INTEGER
"S_REMOTE_CNT", # INTEGER
"S_DATA", # VARCHAR
],
constants.TABLENAME_ORDERS: [
"O_ID", # INTEGER
"O_C_ID", # INTEGER
"O_D_ID", # TINYINT
"O_W_ID", # SMALLINT
"O_ENTRY_D", # TIMESTAMP
"O_CARRIER_ID", # INTEGER
"O_OL_CNT", # INTEGER
"O_ALL_LOCAL", # INTEGER
],
constants.TABLENAME_NEW_ORDER: [
"NO_O_ID", # INTEGER
"NO_D_ID", # TINYINT
"NO_W_ID", # SMALLINT
],
constants.TABLENAME_ORDER_LINE: [
"OL_O_ID", # INTEGER
"OL_D_ID", # TINYINT
"OL_W_ID", # SMALLINT
"OL_NUMBER", # INTEGER
"OL_I_ID", # INTEGER
"OL_SUPPLY_W_ID", # SMALLINT
"OL_DELIVERY_D", # TIMESTAMP
"OL_QUANTITY", # INTEGER
"OL_AMOUNT", # FLOAT
"OL_DIST_INFO", # VARCHAR
],
constants.TABLENAME_HISTORY: [
"H_C_ID", # INTEGER
"H_C_D_ID", # TINYINT
"H_C_W_ID", # SMALLINT
"H_D_ID", # TINYINT
"H_W_ID", # SMALLINT
"H_DATE", # TIMESTAMP
"H_AMOUNT", # FLOAT
"H_DATA", # VARCHAR
],
}
TABLE_INDEXES = {
constants.TABLENAME_ITEM: [
[("I_W_ID", pymongo.ASCENDING), ("I_ID", pymongo.ASCENDING)]
],
constants.TABLENAME_WAREHOUSE: [
[("W_ID", pymongo.ASCENDING), ("W_TAX", pymongo.ASCENDING)]
],
constants.TABLENAME_DISTRICT: [
[("D_W_ID", pymongo.ASCENDING), ("D_ID", pymongo.ASCENDING), ("D_NEXT_O_ID", pymongo.ASCENDING), ("D_TAX", pymongo.ASCENDING)]
],
constants.TABLENAME_CUSTOMER: [
[("C_W_ID", pymongo.ASCENDING), ("C_D_ID", pymongo.ASCENDING), ("C_ID", pymongo.ASCENDING)],
[("C_W_ID", pymongo.ASCENDING), ("C_D_ID", pymongo.ASCENDING), ("C_LAST", pymongo.ASCENDING)]
],
constants.TABLENAME_STOCK: [
[("S_W_ID", pymongo.ASCENDING), ("S_I_ID", pymongo.ASCENDING), ("S_QUANTITY", pymongo.ASCENDING)],
"S_I_ID"
],
constants.TABLENAME_ORDERS: [
[("O_W_ID", pymongo.ASCENDING), ("O_D_ID", pymongo.ASCENDING), ("O_ID", pymongo.ASCENDING), ("O_C_ID", pymongo.ASCENDING)],
[("O_C_ID", pymongo.ASCENDING), ("O_D_ID", pymongo.ASCENDING), ("O_W_ID", pymongo.ASCENDING), ("O_ID", pymongo.DESCENDING), ("O_CARRIER_ID", pymongo.ASCENDING), ("O_ENTRY_ID", pymongo.ASCENDING)]
],
constants.TABLENAME_NEW_ORDER: [
[("NO_W_ID", pymongo.ASCENDING), ("NO_D_ID", pymongo.ASCENDING), ("NO_O_ID", pymongo.ASCENDING)]
],
constants.TABLENAME_ORDER_LINE: [
[("OL_O_ID", pymongo.ASCENDING), ("OL_D_ID", pymongo.ASCENDING), ("OL_W_ID", pymongo.ASCENDING), ("OL_NUMBER", pymongo.ASCENDING)],
[("OL_O_ID", pymongo.ASCENDING), ("OL_D_ID", pymongo.ASCENDING), ("OL_W_ID", pymongo.ASCENDING), ("OL_I_ID", pymongo.DESCENDING), ("OL_AMOUNT", pymongo.ASCENDING)]
],
}
## ==============================================
## MongodbDriver
## ==============================================
class MongodbDriver(AbstractDriver):
DEFAULT_CONFIG = {
"uri": ("The mongodb connection string or URI", "mongodb://localhost:27017"),
"name": ("Database name", "tpcc"),
"denormalize": ("If true, data will be denormalized using MongoDB schema design best practices", True),
"notransactions": ("If true, transactions will not be used (benchmarking only)", False),
"findandmodify": ("If true, all things to update will be fetched via findAndModify", True),
"secondary_reads": ("If true, we will allow secondary reads", True),
"retry_writes": ("If true, we will enable retryable writes", True),
"causal_consistency": ("If true, we will perform causal reads ", True),
"shards": ("If >1 then sharded", "1"),
"ssl": ("If true, PyMongo will be configured to connect to the server using TLS", False),
"ssl_certfile": ("The path to a client certificate", ""),
"ssl_ca_certs": ("The path to a CA file", ""),
"ssl_pem_passphrase": ("The password or passphrase to decrypt encrypted private keys", "")
}
DENORMALIZED_TABLES = [
constants.TABLENAME_ORDERS,
constants.TABLENAME_ORDER_LINE
]
def __init__(self, ddl):
super(MongodbDriver, self).__init__("mongodb", ddl)
self.no_transactions = False
self.find_and_modify = True
self.read_preference = "primary"
self.database = None
self.client = None
self.executed = False
self.w_orders = {}
# things that are not better can't be set in config
self.batch_writes = True
self.agg = False
self.all_in_one_txn = True
# initialize
self.causal_consistency = False
self.secondary_reads = False
self.retry_writes = True
self.read_concern = "majority"
self.write_concern = pymongo.write_concern.WriteConcern(w=1)
self.denormalize = True
self.output = open('results.json','a')
self.result_doc = {}
self.warehouses = 0
self.shards = 1
self.ssl = False
self.ssl_certfile = None
self.ssl_ca_certs = None
self.ssl_pem_passphrase = None
## Create member mapping to collections
for name in constants.ALL_TABLES:
self.__dict__[name.lower()] = None
## ----------------------------------------------
## makeDefaultConfig
## ----------------------------------------------
def makeDefaultConfig(self):
return MongodbDriver.DEFAULT_CONFIG
## ----------------------------------------------
## loadConfig
## ----------------------------------------------
def loadConfig(self, config):
default_uri = 'uri' not in config
for key in MongodbDriver.DEFAULT_CONFIG:
# rather than forcing every value which has a default to be specified
# we should pluck out the keys from default that are missing in config
# and set them there to their default values
if not key in config:
logging.debug("'%s' not in %s conf, set to %s",
key, self.name, str(MongodbDriver.DEFAULT_CONFIG[key][1]))
config[key] = str(MongodbDriver.DEFAULT_CONFIG[key][1])
logging.debug("Default plus our config %s", pformat(config))
self.denormalize = config['denormalize'] == 'True'
self.no_transactions = config['notransactions'] == 'True'
self.shards = int(config['shards'])
self.warehouses = config['warehouses']
self.find_and_modify = config['findandmodify'] == 'True'
self.causal_consistency = config['causal_consistency'] == 'True'
self.retry_writes = config['retry_writes'] == 'True'
self.secondary_reads = config['secondary_reads'] == 'True'
if self.secondary_reads:
self.read_preference = "nearest"
self.ssl = config['ssl'] == 'True'
if self.ssl:
if config['ssl_certfile'] != "":
self.ssl_certfile = config['ssl_certfile']
if config['ssl_ca_certs'] != "":
self.ssl_ca_certs = config['ssl_ca_certs']
if config['ssl_pem_passphrase'] != "":
self.ssl_pem_passphrase = config['ssl_pem_passphrase']
if 'write_concern' in config and config['write_concern'] and config['write_concern'] != '1':
# only expecting string 'majority' as an alternative to w:1
self.write_concern = pymongo.write_concern.WriteConcern(w=str(config['write_concern']), wtimeout=30000)
# handle building connection string
userpassword = ""
usersecret = ""
uri = config['uri']
# only use host/port if they didn't provide URI
if default_uri and 'host' in config:
host = config['host']
if 'port' in config:
host = host+':'+config['port']
uri = "mongodb://" + host
if 'user' in config:
user = config['user']
if not 'passwd' in config:
logging.error("must specify password if user is specified")
sys.exit(1)
userpassword = urllib.quote_plus(user)+':'+urllib.quote_plus(config['passwd'])+"@"
usersecret = urllib.quote_plus(user)+':'+ '*'*len(config['passwd']) + "@"
pindex = 10 # "mongodb://"
if uri[0:14] == "mongodb+srv://":
pindex = 14
real_uri = uri[0:pindex]+userpassword+uri[pindex:]
display_uri = uri[0:pindex]+usersecret+uri[pindex:]
self.client = pymongo.MongoClient(real_uri,
ssl=self.ssl,
ssl_certfile=self.ssl_certfile,
ssl_ca_certs=self.ssl_ca_certs,
ssl_pem_passphrase=self.ssl_pem_passphrase,
retryWrites=self.retry_writes,
readPreference=self.read_preference,
readConcernLevel=self.read_concern)
self.result_doc['before']=self.get_server_status()
# set default writeConcern on the database
self.database = self.client.get_database(name=str(config['name']), write_concern=self.write_concern)
if self.denormalize:
logging.debug("Using denormalized data model")
try:
if config["reset"]:
logging.info("Deleting database '%s'", self.database.name)
for name in constants.ALL_TABLES:
self.database[name].drop()
logging.debug("Dropped collection %s", name)
## FOR
## IF
## whether should check for indexes
load_indexes = ('execute' in config and not config['execute']) and \
('load' in config and not config['load'])
for name in constants.ALL_TABLES:
if self.denormalize and name == "ORDER_LINE":
continue
self.__dict__[name.lower()] = self.database[name]
if load_indexes and name in TABLE_INDEXES:
uniq = True
for index in TABLE_INDEXES[name]:
self.database[name].create_index(index, unique=uniq)
uniq = False
## IF
## FOR
except pymongo.errors.OperationFailure as exc:
logging.error("OperationFailure %d (%s) when connected to %s: ",
exc.code, exc.details, display_uri)
return
except pymongo.errors.ServerSelectionTimeoutError as exc:
logging.error("ServerSelectionTimeoutError %d (%s) when connected to %s: ",
exc.code, exc.details, display_uri)
return
except pymongo.errors.ConnectionFailure:
logging.error("ConnectionFailure %d (%s) when connected to %s: ",
exc.code, exc.details, display_uri)
return
except pymongo.errors.PyMongoError, err:
logging.error("Some general error (%s) when connected to %s: ", str(err), display_uri)
print "Got some other error: %s" % str(err)
return
## ----------------------------------------------
## loadTuples
## ----------------------------------------------
def loadTuples(self, tableName, tuples):
if not tuples:
return
logging.debug("Loading %d tuples for tableName %s", len(tuples), tableName)
assert tableName in TABLE_COLUMNS, "Table %s not found in TABLE_COLUMNS" % tableName
columns = TABLE_COLUMNS[tableName]
num_columns = range(len(columns))
tuple_dicts = []
## We want to combine all of a CUSTOMER's ORDERS, and ORDER_LINE records
## into a single document
if self.denormalize and tableName in MongodbDriver.DENORMALIZED_TABLES:
## If this is the ORDERS table, then we'll just store the record locally for now
if tableName == constants.TABLENAME_ORDERS:
for t in tuples:
key = tuple(t[:1]+t[2:4]) # O_ID, O_C_ID, O_D_ID, O_W_ID
# self.w_orders[key] = dict(map(lambda i: (columns[i], t[i]), num_columns))
self.w_orders[key] = dict([(columns[i], t[i]) for i in num_columns])
## FOR
## IF
## If this is an ORDER_LINE record, then we need to stick it inside of the
## right ORDERS record
elif tableName == constants.TABLENAME_ORDER_LINE:
for t in tuples:
o_key = tuple(t[:3]) # O_ID, O_D_ID, O_W_ID
assert o_key in self.w_orders, "Order Key: %s\nAll Keys:\n%s" % (str(o_key), "\n".join(map(str, sorted(self.w_orders.keys()))))
o = self.w_orders[o_key]
if not tableName in o:
o[tableName] = []
o[tableName].append(dict([(columns[i], t[i]) for i in num_columns[4:]]))
## FOR
## Otherwise nothing
else: assert False, "Only Orders and order lines are denormalized! Got %s." % tableName
## Otherwise just shove the tuples straight to the target collection
else:
if tableName == constants.TABLENAME_ITEM:
tuples3 = []
if self.shards > 1:
ww = range(1,self.warehouses+1)
else:
ww = [0]
for t in tuples:
for w in ww:
t2 = list(t)
t2.append(w)
tuples3.append(t2)
tuples = tuples3
for t in tuples:
tuple_dicts.append(dict([(columns[i], t[i]) for i in num_columns]))
## FOR
self.database[tableName].insert(tuple_dicts)
## IF
return
def loadFinishDistrict(self, w_id, d_id):
if self.denormalize:
logging.debug("Pushing %d denormalized ORDERS records for WAREHOUSE %d DISTRICT %d into MongoDB", len(self.w_orders), w_id, d_id)
self.database[constants.TABLENAME_ORDERS].insert(self.w_orders.values())
self.w_orders.clear()
## IF
def executeStart(self):
"""Optional callback before the execution for each client starts"""
return None
def executeFinish(self):
"""Callback after the execution for each client finishes"""
return None
## ----------------------------------------------
## doDelivery
## ----------------------------------------------
def doDelivery(self, params):
# two options, option one (default) is to run a db transaction for each of 10 orders
if self.all_in_one_txn:
(value, retries) = self.run_transaction_with_retries(self._doDelivery10Txn, "DELIVERY", params)
return (value, retries)
result = []
retries = 0
# there will be as many orders as districts per warehouse (10)
for d_id in range(1, constants.DISTRICTS_PER_WAREHOUSE+1):
params["d_id"] = d_id
(r, rt) = self.run_transaction_with_retries(self._doDeliveryTxn, "DELIVERY", params)
retries += rt
result.append(r)
return (result, retries)
def _doDelivery10Txn(self, s, params):
result = []
# there will be as many orders as districts per warehouse (10)
for d_id in range(1, constants.DISTRICTS_PER_WAREHOUSE+1):
params["d_id"] = d_id
r = self._doDeliveryTxn(s, params)
if r:
result.append(r)
return result
def _doDeliveryTxn(self, s, params):
w_id = params["w_id"]
o_carrier_id = params["o_carrier_id"]
ol_delivery_d = params["ol_delivery_d"]
d_id = params["d_id"]
comment = "DELIVERY " + str(d_id)
## getNewOrder
new_order_query = {"NO_D_ID": d_id, "NO_W_ID": w_id, "$comment": comment}
new_order_project = {"_id":0, "NO_D_ID":1, "NO_W_ID":1, "NO_O_ID": 1}
if self.find_and_modify:
no = self.new_order.find_one_and_delete(new_order_query,
projection=new_order_project,
sort=[("NO_O_ID", 1)], session=s)
if not no:
## No orders for this district: skip it. Note: This must be reported if > 1%
return None
else:
no_cursor = self.new_order.find(new_order_query,
new_order_project,
session=s).sort([("NO_O_ID", 1)]).limit(1)
no_converted_cursor = list(no_cursor)
if not no_converted_cursor:
## No orders for this district: skip it. Note: This must be reported if > 1%
return None
## IF
no = no_converted_cursor[0]
## IF
o_id = no["NO_O_ID"]
assert o_id, "o_id cannot be missing for delivery"
## getCId
order_query = {"O_ID": o_id, "O_D_ID": d_id, "O_W_ID": w_id, "$comment": comment}
if self.denormalize:
if self.find_and_modify:
o = self.orders.find_one_and_update(order_query,
{"$set": {"O_CARRIER_ID": o_carrier_id,
"ORDER_LINE.$[].OL_DELIVERY_D": ol_delivery_d}},
session=s)
else:
o = self.orders.find_one(order_query, session=s)
else:
o = self.orders.find_one(order_query,
{"O_C_ID": 1, "O_ID": 1, "O_D_ID": 1, "O_W_ID": 1, "_id":0},
session=s)
assert o, "o cannot be none, delivery"
c_id = o["O_C_ID"]
if self.denormalize:
## sumOLAmount + updateOrderLine
ol_total = 0
order_lines = o["ORDER_LINE"]
ol_total = sum([ol["OL_AMOUNT"] for ol in order_lines])
assert ol_total > 0, "ol_total is 0"
## updateOrders
if not self.find_and_modify:
self.orders.update_one({"_id": o['_id'], "$comment": comment},
{"$set": {"O_CARRIER_ID": o_carrier_id,
"ORDER_LINE.$[].OL_DELIVERY_D": ol_delivery_d}},
session=s)
else:
## sumOLAmount
order_lines = self.order_line.find({"OL_O_ID": o_id,
"OL_D_ID": d_id,
"OL_W_ID": w_id,
"$comment": comment},
{"_id":0, "OL_AMOUNT": 1}, session=s)
assert order_lines, "order_lines cannot be missing in delivery"
ol_total = sum([ol["OL_AMOUNT"] for ol in order_lines])
## updateOrders
o["$comment"] = comment
self.orders.update_one(o, {"$set": {"O_CARRIER_ID": o_carrier_id}}, session=s)
## updateOrderLines
self.order_line.update_many({"OL_O_ID": o_id, "OL_D_ID": d_id, "OL_W_ID": w_id},
{"$set": {"OL_DELIVERY_D": ol_delivery_d}}, session=s)
## IF
## updateCustomer
self.customer.update_one({"C_ID": c_id, "C_D_ID": d_id, "C_W_ID": w_id, "$comment": comment},
{"$inc": {"C_BALANCE": ol_total}}, session=s)
## deleteNewOrder
if not self.find_and_modify:
self.new_order.delete_one(no, session=s)
# These must be logged in the "result file" according to TPC-C 2.7.2.2 (page 39)
# We remove the queued time, completed time, w_id, and o_carrier_id: the client can figure
# them out
# If there are no order lines, SUM returns null. There should always be order lines.
assert ol_total, "ol_total is NULL: there are no order lines. This should not happen"
assert ol_total > 0.0, "ol_total is 0"
return (d_id, o_id)
## ----------------------------------------------
## doNewOrder
## ----------------------------------------------
def doNewOrder(self, params):
(value, retries) = self.run_transaction_with_retries(self._doNewOrderTxn, "NEW_ORDER", params)
return (value, retries)
def _doNewOrderTxn(self, s, params):
w_id = params["w_id"]
d_id = params["d_id"]
c_id = params["c_id"]
o_entry_d = params["o_entry_d"]
i_ids = params["i_ids"]
i_w_ids = params["i_w_ids"]
i_qtys = params["i_qtys"]
s_dist_col = "S_DIST_%02d" % d_id
comment = "NEW_ORDER"
assert i_ids, "No matching i_ids found for new order"
assert len(i_ids) == len(i_w_ids), "different number of i_ids and i_w_ids"
assert len(i_ids) == len(i_qtys), "different number of i_ids and i_qtys"
## ----------------
## Collect Information from WAREHOUSE, DISTRICT, and CUSTOMER
## ----------------
# getDistrict
district_project = {"_id":0, "D_ID":1, "D_W_ID":1, "D_TAX": 1, "D_NEXT_O_ID": 1}
if self.find_and_modify:
d = self.district.find_one_and_update({"D_ID": d_id, "D_W_ID": w_id, "$comment": comment},
{"$inc":{"D_NEXT_O_ID":1}},
projection=district_project,
sort=[("NO_O_ID", 1)],
session=s)
if not d:
d1 = self.district.find_one({"D_ID": d_id, "D_W_ID": w_id, "$comment": "new order did not find district"})
print d1, w_id, d_id, c_id, i_ids, i_w_ids, s_dist_col
assert d, "Couldn't find district in new order w_id %d d_id %d" % (w_id, d_id)
else:
d = self.district.find_one({"D_ID": d_id, "D_W_ID": w_id, "$comment": comment},
district_project, session=s)
assert d, "Couldn't find district in new order w_id %d d_id %d" % (w_id, d_id)
# incrementNextOrderId
d["$comment"] = comment
self.district.update_one(d, {"$inc": {"D_NEXT_O_ID": 1}}, session=s)
## IF
d_tax = d["D_TAX"]
d_next_o_id = d["D_NEXT_O_ID"]
# fetch matching items and see if they are all valid
if self.shards > 1: i_w_id = w_id
else: i_w_id = 0
items = list(self.item.find({"I_ID": {"$in": i_ids}, "I_W_ID": i_w_id, "$comment": comment},
{"_id":0, "I_ID": 1, "I_PRICE": 1, "I_NAME": 1, "I_DATA": 1},
session=s))
## TPCC defines 1% of neworder gives a wrong itemid, causing rollback.
## Note that this will happen with 1% of transactions on purpose.
if len(items) != len(i_ids):
if not self.no_transactions:
s.abort_transaction()
logging.debug("1% Abort transaction: " + constants.INVALID_ITEM_MESSAGE)
#print constants.INVALID_ITEM_MESSAGE + ", Aborting transaction (ok for 1%)"
return None
## IF
items = sorted(items, key=lambda x: i_ids.index(x['I_ID']))
# getWarehouseTaxRate
w = self.warehouse.find_one({"W_ID": w_id, "$comment": comment}, {"_id":0, "W_TAX": 1}, session=s)
assert w, "Couldn't find warehouse in new order w_id %d" % (w_id)
w_tax = w["W_TAX"]
# getCustomer
c = self.customer.find_one({"C_ID": c_id, "C_D_ID": d_id, "C_W_ID": w_id, "$comment": comment},
{"C_DISCOUNT": 1, "C_LAST": 1, "C_CREDIT": 1}, session=s)
assert c, "Couldn't find customer in new order"
c_discount = c["C_DISCOUNT"]
## ----------------
## Insert Order Information
## ----------------
ol_cnt = len(i_ids)
o_carrier_id = constants.NULL_CARRIER_ID
# createNewOrder
self.new_order.insert_one({"NO_O_ID": d_next_o_id, "NO_D_ID": d_id, "NO_W_ID": w_id}, session=s)
all_local = 1 if ([w_id] * len(i_w_ids)) == i_w_ids else 0
o = {"O_ID": d_next_o_id, "O_ENTRY_D": o_entry_d,
"O_CARRIER_ID": o_carrier_id, "O_OL_CNT": ol_cnt, "O_ALL_LOCAL": all_local}
if self.denormalize:
o[constants.TABLENAME_ORDER_LINE] = []
o["O_D_ID"] = d_id
o["O_W_ID"] = w_id
o["O_C_ID"] = c_id
## ----------------
## OPTIMIZATION:
## If all of the items are at the same warehouse, then we'll issue a single
## request to get their information, otherwise we'll still issue a single request
## ----------------
item_w_list = zip(i_ids, i_w_ids)
stock_project = {"_id":0, "S_I_ID": 1, "S_W_ID": 1,
"S_QUANTITY": 1, "S_DATA": 1, "S_YTD": 1,
"S_ORDER_CNT": 1, "S_REMOTE_CNT": 1, s_dist_col: 1}
if all_local:
all_stocks = list(self.stock.find({"S_I_ID": {"$in": i_ids}, "S_W_ID": w_id, "$comment": comment},
stock_project,
session=s))
else:
field_list = ["S_I_ID", "S_W_ID"]
search_list = [dict(zip(field_list, ze)) for ze in item_w_list]
all_stocks = list(self.stock.find({"$or": search_list, "$comment": comment},
stock_project,
session=s))
## IF
assert len(all_stocks) == ol_cnt, "all_stocks len %d != ol_cnt %d" % (len(all_stocks), ol_cnt)
all_stocks = sorted(all_stocks, key=lambda x: item_w_list.index((x['S_I_ID'], x["S_W_ID"])))
## ----------------
## Insert Order Line, Stock Item Information
## ----------------
item_data = []
total = 0
# we already fetched all items so we should never need to go to self.item again
# iterate over every line item
# if self.batch_writes is set then write once per collection
if self.batch_writes:
stock_writes = []
order_line_writes = []
## IF
for i in range(ol_cnt):
ol_number = i + 1
ol_supply_w_id = i_w_ids[i]
ol_i_id = i_ids[i]
ol_quantity = i_qtys[i]
item_info = items[i]
i_name = item_info["I_NAME"]
i_data = item_info["I_DATA"]
i_price = item_info["I_PRICE"]
si = all_stocks[i]
assert si, "stock item not found"
s_quantity = si["S_QUANTITY"]
s_ytd = si["S_YTD"]
s_order_cnt = si["S_ORDER_CNT"]
s_remote_cnt = si["S_REMOTE_CNT"]
s_data = si["S_DATA"]
s_dist_xx = si[s_dist_col] # Fetches data from the s_dist_[d_id] column
## Update stock
s_ytd += ol_quantity
if s_quantity >= ol_quantity + 10:
s_quantity = s_quantity - ol_quantity
else:
s_quantity = s_quantity + 91 - ol_quantity
## IF
s_order_cnt += 1
if ol_supply_w_id != w_id:
s_remote_cnt += 1
# updateStock
stock_write_update = {"$set": {"S_QUANTITY": s_quantity,
"S_YTD": s_ytd,
"S_ORDER_CNT": s_order_cnt,
"S_REMOTE_CNT": s_remote_cnt}}
if self.batch_writes:
si["$comment"] = comment
stock_writes.append(pymongo.UpdateOne(si, stock_write_update))
else:
si["$comment"] = comment
self.stock.update_one(si, stock_write_update, session=s)
if i_data.find(constants.ORIGINAL_STRING) != -1 and s_data.find(constants.ORIGINAL_STRING) != -1:
brand_generic = 'B'
else:
brand_generic = 'G'
## IF
## Transaction profile states to use "ol_quantity * i_price"
ol_amount = ol_quantity * i_price
total += ol_amount
ol = {"OL_O_ID": d_next_o_id, "OL_NUMBER": ol_number, "OL_I_ID": ol_i_id,
"OL_SUPPLY_W_ID": ol_supply_w_id, "OL_DELIVERY_D": o_entry_d,
"OL_QUANTITY": ol_quantity, "OL_AMOUNT": ol_amount, "OL_DIST_INFO": s_dist_xx}
if self.denormalize:
# createOrderLine
o[constants.TABLENAME_ORDER_LINE].append(ol)
else:
ol["OL_D_ID"] = d_id
ol["OL_W_ID"] = w_id
# createOrderLine
if self.batch_writes:
order_line_writes.append(ol)
else:
self.order_line.insert_one(ol, session=s)
## IF
## IF
## Add the info to be returned
item_data.append((i_name, s_quantity, brand_generic, i_price, ol_amount))
## FOR
## Adjust the total for the discount
total *= (1 - c_discount) * (1 + w_tax + d_tax)
if self.batch_writes:
if not self.denormalize:
self.order_line.insert_many(order_line_writes, session=s)
self.stock.bulk_write(stock_writes, session=s)
## IF
# createOrder
self.orders.insert_one(o, session=s)
## Pack up values the client is missing (see TPC-C 2.4.3.5)
misc = [(w_tax, d_tax, d_next_o_id, total)]
return [c, misc, item_data]
## ----------------------------------------------
## doOrderStatus
## ----------------------------------------------
def doOrderStatus(self, params):
(value, retries) = self.run_transaction_with_retries(self._doOrderStatusTxn, "ORDER_STATUS", params)
return (self._doOrderStatusTxn(None, params), 0)
def _doOrderStatusTxn(self, s, params):
w_id = params["w_id"]
d_id = params["d_id"]
c_id = params["c_id"]
c_last = params["c_last"]
comment = "ORDER_STATUS"
assert w_id, pformat(params)
assert d_id, pformat(params)
search_fields = {"C_W_ID": w_id, "C_D_ID": d_id, "$comment": comment}
return_fields = {"_id":0, "C_ID": 1, "C_FIRST": 1, "C_MIDDLE": 1, "C_LAST": 1, "C_BALANCE": 1}
if c_id != None:
# getCustomerByCustomerId
search_fields["C_ID"] = c_id
c = self.customer.find_one(search_fields, return_fields, session=s)
assert c, "Couldn't find customer in order status"
else:
# getCustomersByLastName
# Get the midpoint customer's id
search_fields['C_LAST'] = c_last
all_customers = list(self.customer.find(search_fields, return_fields, session=s))
namecnt = len(all_customers)
assert namecnt > 0, "No matching customer for last name %s!" % c_last
index = (namecnt-1)/2
c = all_customers[index]
c_id = c["C_ID"]
## IF
assert c_id != None, "Couldn't find c_id in order status"
order_lines = []
order = None
# getLastOrder
if self.denormalize:
order = self.orders.find({"O_W_ID": w_id, "O_D_ID": d_id, "O_C_ID": c_id, "$comment": comment},
{"O_ID": 1, "O_CARRIER_ID": 1, "O_ENTRY_D": 1, "ORDER_LINE":1},
session=s).sort("O_ID", direction=pymongo.DESCENDING).limit(1)[0]
else:
order = self.orders.find({"O_W_ID": w_id, "O_D_ID": d_id, "O_C_ID": c_id, "$comment": comment},
{"O_ID": 1, "O_CARRIER_ID": 1, "O_ENTRY_D": 1},
session=s).sort("O_ID", direction=pymongo.DESCENDING).limit(1)[0]
assert order, "No order found for customer!"
o_id = order["O_ID"]
# getOrderLines
if self.denormalize:
assert constants.TABLENAME_ORDER_LINE in order, "No ORDER_LINE, order %s" % repr(order)
order_lines = order[constants.TABLENAME_ORDER_LINE]
else:
order_lines = self.order_line.find({"OL_W_ID": w_id, "OL_D_ID": d_id, "OL_O_ID": o_id,
"$comment": comment},
{"OL_SUPPLY_W_ID": 1,
"OL_I_ID": 1,
"OL_QUANTITY": 1,
"OL_AMOUNT": 1,
"OL_DELIVERY_D": 1}, session=s)
## IF
return [c, order, order_lines]
## ----------------------------------------------
## doPayment
## ----------------------------------------------
def doPayment(self, params):
(value, retries) = self.run_transaction_with_retries(self._doPaymentTxn, "PAYMENT", params)
return (value, retries)
def _doPaymentTxn(self, s, params):
w_id = params["w_id"]
d_id = params["d_id"]
h_amount = params["h_amount"]
c_w_id = params["c_w_id"]
c_d_id = params["c_d_id"]
c_id = params["c_id"]
c_last = params["c_last"]
h_date = params["h_date"]
comment = "PAYMENT"
# getDistrict
district_project = {"D_NAME": 1,
"D_STREET_1": 1,
"D_STREET_2": 1,
"D_CITY": 1,
"D_STATE": 1,
"D_ZIP": 1}
if self.find_and_modify:
d = self.district.find_one_and_update({"D_ID": d_id, "D_W_ID": w_id,
"$comment": comment},
{"$inc":{"D_YTD":h_amount}},
projection=district_project,
session=s)
if not d:
d1 = self.district.find_one({"D_ID": d_id, "D_W_ID": w_id, "$comment": "payment did not find district"})
print d1, w_id, d_id, h_amount, c_w_id, c_d_id, c_id, c_last, h_date
assert d, "Couldn't find district in payment w_id %d d_id %d" % (w_id, d_id)
else:
d = self.district.find_one({"D_W_ID": w_id, "D_ID": d_id, "$comment": comment},
district_project,
session=s)
assert d, "Couldn't find district in payment w_id %d d_id %d" % (w_id, d_id)
# updateDistrictBalance
self.district.update_one({"_id": d["_id"], "$comment": comment},
{"$inc": {"D_YTD": h_amount}}, session=s)
## IF
warehouse_project = {"W_NAME": 1,
"W_STREET_1": 1,
"W_STREET_2": 1,
"W_CITY": 1,
"W_STATE": 1,
"W_ZIP": 1}
if self.find_and_modify:
w = self.warehouse.find_one_and_update({"W_ID": w_id, "$comment": comment},
{"$inc":{"W_YTD":h_amount}},
projection=warehouse_project,
session=s)
assert w, "Couldn't find warehouse in payment w_id %d" % (w_id)
else:
# getWarehouse
w = self.warehouse.find_one({"W_ID": w_id, "$comment": comment},
warehouse_project,
session=s)
assert w, "Couldn't find warehouse in payment w_id %d" % (w_id)
# updateWarehouseBalance
self.warehouse.update_one({"_id": w["_id"], "$comment": comment},
{"$inc": {"W_YTD": h_amount}},
session=s)
## IF
search_fields = {"C_W_ID": w_id, "C_D_ID": d_id, "$comment": comment}
return_fields = {"C_BALANCE": 0, "C_YTD_PAYMENT": 0, "C_PAYMENT_CNT": 0}
if c_id != None:
# getCustomerByCustomerId
search_fields["C_ID"] = c_id
c = self.customer.find_one(search_fields, return_fields, session=s)
assert c, "No customer in payment w_id %d d_id %d c_id %d" % (w_id, d_id, c_id)
else:
# getCustomersByLastName
# Get the midpoint customer's id
search_fields['C_LAST'] = c_last
all_customers = list(self.customer.find(search_fields, return_fields, session=s))
namecnt = len(all_customers)
assert namecnt > 0, "No matching customer w %d d %d clast %s" % (w_id, d_id, c_last)
index = (namecnt-1)/2
c = all_customers[index]
c_id = c["C_ID"]
## IF
assert c_id != None, "Didn't find any matching c_id"
c_data = c["C_DATA"]
# Build CUSTOMER update command
customer_update = {"$inc": {"C_BALANCE": h_amount*-1,
"C_YTD_PAYMENT": h_amount,
"C_PAYMENT_CNT": 1}}
# Customer Credit Information
if c["C_CREDIT"] == constants.BAD_CREDIT:
new_data = " ".join(map(str, [c_id, c_d_id, c_w_id, d_id, w_id, h_amount]))
c_data = (new_data + "|" + c_data)
if len(c_data) > constants.MAX_C_DATA:
c_data = c_data[:constants.MAX_C_DATA]
customer_update["$set"] = {"C_DATA": c_data}
## IF
# Concatenate w_name, four spaces, d_name
h_data = "%s %s" % (w["W_NAME"], d["D_NAME"])
h = {"H_D_ID": d_id,
"H_W_ID": w_id,
"H_DATE": h_date,
"H_AMOUNT": h_amount,
"H_DATA": h_data}
# updateCustomer
self.customer.update_one({"_id": c["_id"], "$comment": comment}, customer_update, session=s)
# insertHistory