-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestpg001.dart
2200 lines (1901 loc) · 74.9 KB
/
testpg001.dart
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
/*
* Program to test PostgrSQL using "postgresql" driver on Dart. License: BSD
*
* 02-Jul-2013 Brian OHara Commenced initial version.
*
* 16-Jul-2013 Brian OHara Altered from async terminal-input to sync.
* (brianoh) Terminal-input was initially designed for
* async, so it is therefore now rather verbose
* as a result of initially writing for async
* console parameterized-input.
*
* 18-Jul-2013 Brian OHara Wrote the minimalist ClassCcy for Currency.
*
* 31-Jul-2013 Brian OHara Handle Db SocketException better. Handle read
* of fixed-length List from file.
*
* 01-Aug-2013 Brian OHara Create a table "random" to store the list of
* (brianoh) keys to be updated in order to test contention
* better. IE. all processes to use same keys for
* updates in order to cause more collisions.
*
* 02-Aug-2013 Brian OHara Removed the start-time as a means of achieving
* (brianoh) a near-synchronous state between instances and
* use 'control' table instead.
*
* 03-Aug-2013 Brian OHara Added the 'totals' table as a means of comparing
* (brianoh) with the selected totals on completion.
*
* 05-Aug-2013 Brian OHara Introduced some errors in order to test the
* (brianoh) error-handling, and made changes to improve
* the error-handling.
*
* 06-Aug-2013 Brian OHara Display of totals and comparison to determine
* if inserts and updates balance with table
* values.
*
* 08-Aug-2013 Brian OHara Put in code for semaphore to detect first
* process to start.
*
* 09-Aug-2013 Brian OHara Test error-handling.
*
* 14-Aug-2013 Brian OHara Create Tables etc.
*
* 15-Aug-2013 Brian OHara Added option to use AutoInc or program-
* generated id.
*
* 18-Aug-2013 Brian OHara Re-wrote the handling of totals to make it
* more streamlined.
*
* 22-Aug-2013 Brian OHara Started testing on Linux (Ubuntu 13.04 64 bit).
* Results illustrate a problem somewhere.
*
* 22-Aug-2013 Brian OHara Reported on Github the problems with times
* on 64-bit Ubuntu (probably related to the VM
* or PostgreSQL RDBMS).
*
* 22-Aug-2013 Brian OHara Tested on 32-bit Linux (Ubuntu 13.04).
* Results good.
*
* 23-Aug-2013 Brian OHara Started testing on Win8 - results good.
*
* ------------------------------------------------------------------------
*
* The purpose of this program is to test the database driver, it is not
* intended as an example of async programming. I've written this in my
* spare time to start learning Dart.
*
* Thanks to Greg for writing the driver and thanks also to the architects
* and developers of Dart and the Dart team and to Google for creating a
* great programming language and environment. Assuming that the Ubuntu
* 64-bit problems relate to something other than Greg's code, I have not
* been able to fault Greg's driver to-date after a lot of trying,
*
* Please advise any suggestions or problems via "issues". Any suggestions
* are very welcome. I'm very much still the student.
*
* One purpose of this program is to enable the ability to put the "system"
* under stress and also stress the database and the driver and create
* collisions in the database in order to test contention. Hopefully, it will
* also help as an example, but as I am still very much a student of Dart,
* any help would be appreciated. I know that much of what has been done
* here can be done better.
*
* With regard to the number of iterations, a larger number (1000+) likely
* gives a better indication of speed. With regard to the sample size, a
* smaller size likely tests contention better, and a larger sample likely
* gives a better indication of speed. A very-small sample-size will also
* likely not be a good indicator of speed in any situation. With multiple
* instances they will likely be queuing to update, and with a small number
* of instances the data will likely be in cache, but it still may not be
* super-fast with one user and a very small update sample.
*
* I have written a virtually identical program to this test program for
* Sqljocky (mysql) which will be loaded onto Github also (when I
* incorporate latest changes).
*
* Perhaps someone could look at some of the async handling and error-
* handling for correctness or for 'better' ways to do it.
*
* The ClassConsole etc. may be overkill, however it was initially written
* for async console input and may have been of use then. However, I have
* found it quite simple to add or remove fields (being familiar with it).
* If of any use, it could be significantly enhanced, keeping in mind that
* HTML should probably be used for all "terminal" input in general.
*
* The layout of tables can be seen in Function fCreateTablesEtc. The
* database requires the following tables (which it creates) :
* test01 - the main table that is updated
* sequences - the table for generating Primary Keys
* control - table for synchronizing instances of program.
* random - the table used for list of keys to be updated.
* totals - the table used for storing and balancing totals
*
* Dart - postgresql - transactionStatus
* -------------------------------------
* TRANSACTION_UNKNOWN = 1;
* TRANSACTION_NONE = 2;
* TRANSACTION_BEGUN = 3;
* TRANSACTION_ERROR = 4;
*/
import 'dart:async' as async;
import 'dart:io';
import 'dart:math';
////import '../../postgresql/lib/postgresql.dart' as pg;
import 'package:postgresql/postgresql.dart' as pg;
const int I_TOTAL_PROMPTS = 11; // the total count of prompts
const int I_MAX_PROMPT = 10; // (data-entry 0 to 10)
const int I_MAX_PARAM = 9; // maximum parameter number (0 to 9)
const int I_DB_USER = 0; // prompt nr
const int I_DB_PWD = 1; // prompt nr
const int I_DB_NAME = 2; // prompt nr
const int I_MAX_INSERTS = 3; // prompt nr
const int I_USE_AUTOINC = 4; // prompt nr
const int I_MAX_UPDATES = 5; // prompt nr
const int I_SELECT_SIZE = 6; // prompt nr
const int I_CLEAR_YN = 7; // prompt nr
const int I_SAVE_YN = 8; // prompt nr
const int I_INSTANCE_TOT = 9; // prompt nr
const int I_CORRECT_YN = 10; // prompt nr
const int I_DEC_PLACES = 2; // decimal places for currency
const int I_TOT_OPEN = 0;
const int I_TOT_INSERT = 1;
const int I_TOT_UPDATE = 2;
const String S_CCY_SYMBOL = "\$";
const String S_CONNECT_TO_DB = "Connect to Database";
const String S_CONTROL_KEY = "1001"; // Key to control table
const String S_DEC_SEP = "."; // Decimal separator
const String S_SEQUENCE_KEY_MAIN = "1001"; // Key to 'test01' table.
const String S_SEQUENCE_KEY_TOTALS = "1002"; // key to 'totals' table
const String S_MAIN_TABLE = "test01"; // the main table used
const String S_THOU_SEP = ","; // Thousands separator
const String S_PARAMS_FILE_NAME = "testPg001.txt";
ClassCcy ogCcy = new ClassCcy(I_DEC_PLACES);
ClassTerminalInput ogTerminalInput = new ClassTerminalInput();
ClassFormatCcy ogFormatCcy = new ClassFormatCcy(I_DEC_PLACES,
S_DEC_SEP, S_THOU_SEP,
S_CCY_SYMBOL);
ClassPrintLine ogPrintLine = new ClassPrintLine(true);
ClassRandNames ogRandNames = new ClassRandNames();
ClassRandAmt ogRandAmt = new ClassRandAmt(I_DEC_PLACES);
pg.Connection ogDb; // postgres connection
RawServerSocket ogSocket;
void main() {
/*
* Get the user selections (program parameters)
*/
List<String> lsInput = ogTerminalInput.fGetUserSelections();
bool tClearMain = (lsInput[I_CLEAR_YN] == "y");
bool tFirstInstance;
bool tUseAutoInc = (lsInput[I_USE_AUTOINC] == "y");
ClassTotals oClassTotals = new ClassTotals();
ClassWrapInt oiClassInt = new ClassWrapInt();
ClassWrapList ollClassList = new ClassWrapList();
int iMaxUpdates = int.parse(lsInput[I_MAX_UPDATES]);
int iInstanceMax = int.parse(lsInput[I_INSTANCE_TOT]);
int iInstanceNr = 0; // each instance has a unique number
int iMaxInserts = int.parse(lsInput[I_MAX_INSERTS]);
int iSelectMax = int.parse(lsInput[I_SELECT_SIZE]);
/*
* Connect to database
*/
final String sUri = "postgres://${lsInput[I_DB_USER]}:"+
"${lsInput[I_DB_PWD]} @localhost:5432/"+
"${lsInput[I_DB_NAME]}";
pg.connect(sUri)
.catchError((oError) {
print ("Main:pg.connect - Database connection not active");
fExit(1);
})
.then((pg.Connection oDb) {
ogDb = oDb; // assign to global database object or connection
fCheckTransactionStatus("pg.connect", false);
/*
* Test database connection.
*/
ogPrintLine.fPrintForce("Testing Db connection .....");
return fTestConnection();
}).then((bool tResult) {
if (tResult != true && tResult != false)
fFatal ("Main", "Result from fTestConnection invalid");
if (tResult != true) {
print ("Main: Database connection is not active");
fExit(1);
}
ogPrintLine.fPrintForce("Database connection now tested");
/*
* Test if this is the first Instance of the program running
*/
return fCheckIfFirstInstance();
}).then((tResult) {
tFirstInstance = tResult;
ogPrintLine.fPrintForce(tFirstInstance ?
"This is the first Instance of program" :
"This is not the first instance of program");
if (!tFirstInstance && iInstanceMax == 1)
throw("This should be the first instance, however "+
" there is an instance already running");
/*
* create tables etc. if necessary
*/
return (!tFirstInstance) ? true : fCreateTablesEtc(tClearMain);
}).then((tResult) {
if (tResult != true)
fFatal("Main", "On return from fCreateTablesEtc. result not "+
"'true' but ${tResult}");
/*
* Instances other than first instance will wait for 1st instance
*/
return tFirstInstance ? true :
fWaitForProcess(sColumn: "iCount1", sCompareType: ">",
iRequiredValue: 0, sWaitReason: "to initialize",
tStart:true);
}).then((tResult) {
if (tResult != true)
fFatal ("Main:fWaitForProcess", "(iCount1) Process failed. Result = ${tResult}");
/*
* Update control row to increment count of instances started
*/
int iRequiredCount = tFirstInstance ? 0 : -1; // 1st instance must be first
return fUpdateControlTableColumn(sColumn: "iCount1",
iRequiredCount: iRequiredCount,
iMaxCount: iInstanceMax,
oiResult: oiClassInt);
}).then((bool tResult) {
iInstanceNr = oiClassInt.iValue; // unique instance number
if (tFirstInstance && iInstanceNr != 1)
fFatal("Main:fUpdateControlTableColumn",
"First instance, but instance nr. = ${iInstanceNr}");
/*
* wait for All processes to Start
*/
return fWaitForProcess(sColumn: "iCount1", sCompareType: "=",
iRequiredValue: iInstanceMax, sWaitReason: "to start processing",
tStart:true);
}).then((tResult) {
if (tResult != true)
fFatal("Main:fWaitForProcess", "Process failed. Result = ${tResult}");
/*
* Process Inserts
*/
ogPrintLine.fPrintForce ("Main processing has commenced ......\n");
return fProcessMainInserts(iInstanceNr, iMaxInserts,
tUseAutoInc, oClassTotals);
}).then((bool tResult) {
if (tResult != true)
fFatal("main:fProcessMainInserts", "Process failed. Result = ${tResult}");
/*
* Display and Insert totals
*/
oClassTotals.fPrint(); // display totals
return fInsertIntoTotalsTable(oClassTotals);
})
.catchError((oError) => fFatal ("Main", "fInsertIntoTotalsTable (Inserts) "+
"Error = ${oError}"))
.then((bool tResult) {
if (tResult != true)
fFatal("Main:fInsertIntoTotalsTable", "Procedd failed: result = ${tResult}");
fCheckTransactionStatus("Main: after fInsertIntoTotalsTable", true);
/*
* Update 'control' to show inserts have completed
*/
return fUpdateControlTableColumn(sColumn: "iCount2",
iRequiredCount: -1,
iMaxCount: iInstanceMax);
}).then((bool tResult) {
if (tResult != true)
fFatal("Main:fUpdateControlTableColumn",
"(iCount2) Process failed. Result = ${tResult}");
fCheckTransactionStatus("Main: after fUpdateControlTableColumn (iCount2)", true);
/*
* wait for All processes to complete main Inserts
*/
return fWaitForProcess(sColumn: "iCount2", sCompareType: "=",
iRequiredValue: iInstanceMax, sWaitReason: "to complete inserts",
tStart:true);
}).then((bool tResult) {
if (tResult != true)
fFatal("Main:fWaitForProcess", "(iCount2) Process failed: result = ${tResult}");
print ("");
/*
* Insert Random keys into 'random' table
*/
ogPrintLine.fPrintForce("Insert table of random keys");
return !tFirstInstance ? true : fInsertRandomKeys(iSelectMax);
}).then((tResult) {
if (tResult != true)
fFatal("Main:fInsertRandomKeys", "failed to insert random keys");
if (tFirstInstance)
ogPrintLine.fPrint("Random keys table created");
/*
* first instance to update control table to show random keys created
*/
return !tFirstInstance ? true :
fUpdateControlTableColumn(sColumn: "iCount3",
iRequiredCount: 0,
iMaxCount: 1);
}).then((bool tResult) {
if (tResult != true)
fFatal("Main:fUpdateControlTable", "(iCount3) Process failed. Result = ${tResult}");
/*
* Instances to wait for 'random' table to be completed
*/
return fWaitForProcess(sColumn: "iCount3", sCompareType: ">",
iRequiredValue: 0, sWaitReason: "to complete random key table propagation",
tStart:true);
}).then((bool tResult) {
if (tResult != true)
fFatal("Main:tWaitForProcess:", "(iCount3) Process failed. Result = ${tResult}");
/*
* Select random table for keys to use for updates
*/
ogPrintLine.fPrintForce("Selecting random keys from random table");
print("");
String sSql = "SELECT ikey FROM random";
return fProcessSqlSelect(sSql, false, ollClassList); /////xxxx
}).then((bool tResult) {
if (tResult != true)
fFatal("Main:fProcessSqlSelect:", "(random) Process failed. Result = ${tResult}");
List<List> llRandKeys = ollClassList.llValue;
if (llRandKeys == null)
fFatal("Main:fProcessSqlSelect:", "Process failed to Select random keys");
ogPrintLine.fPrintForce("Table of Random Keys selected\n");
/*
* Process Updates using random keys
*/
return fProcessMainUpdates(iInstanceNr, iMaxUpdates, llRandKeys, oClassTotals);
}).then((bool tResult) {
if (tResult != true)
fFatal("Main", "fProcessMainUpdates failed");
/*
* Inserts total for Updates
*/
oClassTotals.fPrint();
return fInsertIntoTotalsTable(oClassTotals);
}).then((bool tResult) {
if (tResult != true)
fFatal("Main", "Insert into 'totals' (Updates) failed");
print("");
/*
* Select table Main Table (unsorted)
*/
String sSql = "SELECT * FROM ${S_MAIN_TABLE}";
ogPrintLine.fPrintForce ("Processing Select (Unsorted)");
return fProcessSqlSelect(sSql, true, null);
}).then((bool tResult) {
if (tResult != true)
fFatal("FMain:fProcessSqlSelect",
"${S_MAIN_TABLE} (unsorted) Process failed. Result = ${tResult}");
/*
* Select Main Table (sorted)
*/
String sSql = "SELECT * FROM ${S_MAIN_TABLE} ORDER BY ikey";
ogPrintLine.fPrintForce ("Processing Select (Sorted)");
return fProcessSqlSelect(sSql, true, null);
}).then((bool tResult) {
if (tResult != true)
fFatal("FMain:fProcessSqlSelect",
"${S_MAIN_TABLE} (sorted) Process failed. Result = ${tResult}");
/*
* Update control row to increment count of instances finished
*/
return fUpdateControlTableColumn(sColumn: "iCount4",
iRequiredCount: -1,
iMaxCount: iInstanceMax);
}).then((bool tResult) {
if (tResult != true)
fFatal("Main:fUpdateControlTable", "(iCount4) Process failed. Result = ${tResult}");
return fWaitForProcess(sColumn: "iCount4", sCompareType: "=",
iRequiredValue: iInstanceMax, sWaitReason: "to complete updates",
tStart:false);
}).then((bool tResult) {
if (tResult != true)
fFatal ("Main:fWaitForProcess", "(iCount1) Process failed. Result = ${tResult}");
/*
* Select totals from main table
*/
print ("");
fDisplayTotals().then((_) {
ogPrintLine.fPrintForce("Completed");
fExit(0);
});
}).catchError((oError) {
fFatal("Main", "Error = ${oError}");
});
}
/*
* Process Inserts To main Table
*/
async.Future<bool> fProcessMainInserts(int iInstanceNr, int iMaxIters,
bool tUseAutoInc,
ClassTotals oClassTotals) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
Function fLoopMainInserts;
int iDiv = fGetDivisor(iMaxIters); // iDiv is divisor for progress indic.
int iInsertFailTot = 0;
int iCcyInsertTot = 0;
int iInsertTotNr = 0;
int iLastIdTot = 0;
int iLastLog = 0;
Stopwatch oStopwatch = new Stopwatch();
fLoopMainInserts = () {
if (iInsertTotNr >= iMaxIters) { // All Inserts have completed
oStopwatch.stop;
if (iInsertTotNr != iLastLog)
stdout.write ("${iInsertTotNr}");
print("");
fCheckTransactionStatus("fProcessMainInserts - completed", false);
ogPrintLine.fPrintForce("Failed Inserts (system stress) = "+
"${iInsertFailTot}");
if (tUseAutoInc)
ogPrintLine.fPrintForce("AutoInc Id's retrieved = ${iLastIdTot}");
oClassTotals.fSetValues (iInstance : iInstanceNr,
iTotType : I_TOT_INSERT,
iInsertTotNr : iInsertTotNr,
iUpdateTotNr : 0,
iCcyTotAmt : iCcyInsertTot,
iTotMillis : oStopwatch.elapsedMilliseconds);
oCompleter.complete(true);
return;
}
if (iInsertFailTot >= 100 && iInsertFailTot > iInsertTotNr)
fFatal("fProcessMainInserts", "Aborted - ${iInsertFailTot} failed inserts, "+
" ${iInsertTotNr} succeeded");
if (iInsertTotNr % iDiv == 0 && iInsertTotNr != iLastLog) {
stdout.write("${iInsertTotNr} ");
iLastLog = iInsertTotNr;
}
bool tPositive = (iInsertTotNr % 2 == 0); // to generate pos or neg value
int iCcyBal = ogRandAmt.fRandAmt(99999, tPositive); // Generate random $cc
String sCcyBal = ogCcy.fCcyIntToString(iCcyBal);
String sName = ogRandNames.fGetRandName();
/////xxxx put code here to test errors
if (!(tUseAutoInc)) { // Don't use autoincrement
String sSql = "(iKey, sname, dbalance) "+
"VALUES (?, '$sName', $sCcyBal)";
fInsertRowWithSequence(S_MAIN_TABLE, S_SEQUENCE_KEY_MAIN, sSql)
.then((tResult) {
if (!(tResult))
iInsertFailTot++;
else {
iCcyInsertTot += iCcyBal;
iInsertTotNr++;
}
fLoopMainInserts();
}).catchError((oError) {
iInsertFailTot ++;
fRollback("fProcessMainInserts");
fLoopMainInserts();
});
} else { // use autoincrement
ClassWrapList ollClassList = new ClassWrapList();
String sSql = "INSERT INTO ${S_MAIN_TABLE} (sname, dbalance)"+
" VALUES ('$sName', $sCcyBal)";
fExecuteSql(sSql, "S_MAIN_TABLE", "fProcessMainInserts", 1)
.catchError((oError) {
iInsertFailTot++;
fLoopMainInserts();
})
.then((tResult) {
if (!(tResult))
iInsertFailTot++;
else {
iInsertTotNr++;
iCcyInsertTot += iCcyBal;
fProcessSqlSelect("SELECT LASTVAL()", false, ollClassList)
.then((bool tResult) {
List<List> llResult = ollClassList.llValue;
if (llResult != null && llResult.length == 1) {
int iKey = llResult[0][0];
if (iKey > 0)
iLastIdTot++;
}
fLoopMainInserts();
}).catchError((_) => fLoopMainInserts);
}
}).catchError((oError) {
iInsertFailTot ++;
fRollback("fProcessMainInserts").then((_) =>
fLoopMainInserts());
});
}
};
ogPrintLine.fWriteForce ("Processing Inserts .... ");
oStopwatch.reset();
oStopwatch.start();
fCheckTransactionStatus("fProcessMainInserts - commmencing", true);
fLoopMainInserts();
return oCompleter.future;
}
/*
* Process Updates for Main Table
*/
async.Future<bool> fProcessMainUpdates(int iInstanceNr, int iMaxIters,
List<List<int>> lliRandKeys,
ClassTotals oClassTotals) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
Function fLoopMainUpdates;
int iCcyUpdateTot = 0;
int iDiv = fGetDivisor(iMaxIters);
int iUpdateTotNr = 0;
int iUpdateFailTot = 0;
int iLastLog = 0;
Random oRandom = new Random();
Stopwatch oStopwatch = new Stopwatch();
fCheckTransactionStatus("fProcessMainUpdates", true);
if (iMaxIters > 0 && lliRandKeys == null)
throw new Exception("fProcessMainUpdates: list of keys not created");
print ("");
if (iMaxIters > 0 && lliRandKeys.isEmpty) {
ogPrintLine.fPrintForce("Starting Updates - No Random Keys have been "+
"selected for Update");
oCompleter.complete(true);
return oCompleter.future;
}
ogPrintLine.fWriteForce ("Starting Updates .... ");
int iLoopTot = 0;
fLoopMainUpdates = () {
if (iUpdateTotNr >= iMaxIters) {
oStopwatch.stop;
if (iUpdateTotNr != iLastLog)
stdout.write ("${iUpdateTotNr}");
print("");
ogPrintLine.fPrintForce ("Failed updates = ${iUpdateFailTot}");
fCheckTransactionStatus("fProcessMainUpdates - completed", false);
oClassTotals.fSetValues (iInstance : iInstanceNr,
iTotType : I_TOT_UPDATE,
iInsertTotNr : 0,
iUpdateTotNr : iUpdateTotNr,
iCcyTotAmt : iCcyUpdateTot,
iTotMillis : oStopwatch.elapsedMilliseconds);
oCompleter.complete(true);
return;
}
if (iUpdateTotNr % iDiv == 0 && iUpdateTotNr != iLastLog) {
stdout.write ("${iUpdateTotNr} ");
iLastLog = iUpdateTotNr;
}
if (iUpdateFailTot > 100 && iUpdateFailTot > iUpdateTotNr)
fFatal("fProcessMainUpdates", "${iUpdateFailTot} Updates failed, "+
"${iUpdateTotNr} succeeded");
int iKey = lliRandKeys[oRandom.nextInt(lliRandKeys.length)][0];
int iCcyTranAmt = ogRandAmt.fRandAmt(999, (iUpdateTotNr % 2 == 0));
fUpdateSingleMainRow(iKey, iCcyTranAmt).then((tResult) {
if (tResult != true)
iUpdateFailTot++;
else {
iUpdateTotNr ++;
iCcyUpdateTot += iCcyTranAmt;
}
fLoopMainUpdates();
}).catchError((oError) {
iUpdateFailTot++;
fLoopMainUpdates();
});
};
oStopwatch.start();
fCheckTransactionStatus("fProcessMainUpdates - commenced", true);
fLoopMainUpdates();
return oCompleter.future;
}
/*
* Update a Single Row of main table
*/
async.Future<bool> fUpdateSingleMainRow(int iKey, int iCcyTranAmt) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
fCheckTransactionStatus("fUpdateSingleMainRow", true);
String sSql;
ogDb.execute("begin").then((_) {
sSql = "SELECT ikey, dbalance FROM ${S_MAIN_TABLE} "+
"WHERE ikey = ${iKey} FOR UPDATE";
return ogDb.query(sSql).toList();
}).then((lResult){
if (lResult == null || lResult.isEmpty || lResult.length != 1)
throw("fUpdateSingleMainRow: failed to Select ikey = ${iKey}");
String sKey = "${lResult[0][0]}";
String sBalOld = lResult[0][1];
double dBalOld = double.parse(sBalOld);
String sCcyTranAmt = ogCcy.fCcyIntToString(iCcyTranAmt);
double dBalNew = ogCcy.fAddCcyDoubles(dBalOld, double.parse(sCcyTranAmt));
String sNewBal = dBalNew.toStringAsFixed(I_DEC_PLACES);
sSql = "UPDATE ${S_MAIN_TABLE} SET dBalance = $sNewBal WHERE ikey = $sKey";
ogDb.execute(sSql).then((int iRowsAffected) {
if (iRowsAffected != 1)
throw("Rows affected = ${iRowsAffected}, should = 1");
ogDb.execute("COMMIT");
})
.catchError((oError) => throw(oError))
.then((_) {
oCompleter.complete(true);
});
}).catchError((oError) {
print ("fUpdateSingleMainRow: Update failed. Error = ${oError}");
oCompleter.complete(false);
});
return oCompleter.future;
}
/*
* Update Control Table with counter to handle synchronization.
*/
async.Future<bool> fUpdateControlTableColumn({String sColumn,
int iRequiredCount,
int iMaxCount,
ClassWrapInt oiResult}) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
fCheckTransactionStatus("fUpdateControlTableColumn", true);
int iCount;
String sSql;
ogDb.execute("begin").then((_) {
sSql ="SELECT ${sColumn} FROM control WHERE "+
"ikey = $S_CONTROL_KEY FOR UPDATE";
return ogDb.query(sSql).toList().catchError((oError) => throw(oError));
}).then((llResult){
if (llResult == null || llResult.isEmpty || llResult.length != 1)
throw("fUpdateControlTableColumn: failed to Select "+
"ikey = $S_CONTROL_KEY");
iCount = llResult[0][0];
if (iCount >= iMaxCount)
throw ("fUpdateControlTableColumn: Fatal Error - Maximum count = "+
"${iMaxCount}, current count = ${iCount}");
if (iRequiredCount >= 0 && iCount != iRequiredCount)
throw ("fUpdateControlTableColumn: Required count = ${iRequiredCount}, "+
"Current count = ${iCount}");
sSql = "UPDATE control SET ${sColumn} = ${++iCount} "+
"WHERE ikey = $S_CONTROL_KEY";
return ogDb.execute(sSql)
.catchError((oError) => throw(oError))
.then((int iRowsAffected) {
if (iRowsAffected != 1)
throw("Rows affected not 1, but ${iRowsAffected}");
return (ogDb.execute("commit"))
.catchError((oError) => throw(oError))
.then((_) {
fCheckTransactionStatus("fUpdateControlTableColumn-AfterCommit", true);
if (oiResult != null) // calling function wants result
oiResult.iValue = iCount; // set result for calling function
oCompleter.complete(true);
});
});
}).catchError((oError) {
fFatal("fUpdateControlTableColumn", "${oError} - Sql = $sSql");
});
return oCompleter.future;
}
/*
* Insert the List of random keys into table for selection
*/
async.Future<bool> fInsertRandomKeys(int iSelectTot) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
ClassWrapList ollClassList = new ClassWrapList();
Function fLoopRandomInserts;
int iPos = 0;
List<List<int>> lliKeys;
fLoopRandomInserts = () {
if (iPos >= lliKeys.length)
return;
int iKey = lliKeys[iPos][0];
String sSql = "INSERT INTO random (iKey) VALUES (${iKey})";
return fExecuteSql(sSql, "random", "fInsertRandomKeys", 1)
.then((bool tResult){
if (tResult == true)
iPos++;
fLoopRandomInserts();
}).catchError((oError) =>
throw ("fInsertRandomKeys: (${iPos}) ${oError}"));
};
String sSql = "SELECT ikey FROM ${S_MAIN_TABLE} ORDER BY RANDOM() " +
"LIMIT ${iSelectTot}";
fProcessSqlSelect(sSql, false, ollClassList)
.then((bool tResult) {
lliKeys = ollClassList.llValue;
if (lliKeys == null)
throw ("fInsertRandomKeys: Select of keys from "+
"${S_MAIN_TABLE} failed");
ogPrintLine.fPrintForce("${lliKeys.length} random row(s) selected");
fLoopRandomInserts();
oCompleter.complete(true);
return;
}).catchError((oError) {
fFatal("fInsertRandomKeys", "${oError}");
});
return oCompleter.future;
}
/*
* Wait for other instances to complete. The "control" table
* handles synchronization by updating counters and then
* waiting for a required number (of instances) to have completed
* their update.
*/
async.Future<bool> fWaitForProcess({String sColumn,
String sCompareType,
int iRequiredValue,
String sWaitReason,
bool tStart}) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
ClassWrapList ollClassList = new ClassWrapList();
Function fWaitLoop;
int iLastCount;
int iLoopCount = 0;
fWaitLoop = () {
/*
* The sleep is only one second in order that there is not an
* excessive wait after all are "ready". This could be handled
* better (using this methodology), but it would be a little more
* complex. I'll likely change this.
*/
new async.Timer(new Duration(seconds:1), () {
String sSql = "Select ${sColumn} from control where ikey = "+
"$S_CONTROL_KEY";
fProcessSqlSelect(sSql, false, ollClassList)
.then((bool tResult) {
bool tMatched = false; // init
List<List> llRow = ollClassList.llValue; // get the list
if (llRow == null || llRow.length != 1)
fFatal("fWaitForProcess", "Failed to sSelect control row");
int iCount = llRow[0][0];
if (iCount != iLastCount) {
iLastCount = iCount;
String sInstances = iCount == 1 ? "instance has" :"instances have";
String sPline = "${iCount} ${sInstances}";
sPline += tStart ? " started." : " completed.";
tMatched = ((sCompareType == "=" && iCount == iRequiredValue)
|| (sCompareType == ">" && iCount > iRequiredValue));
if (!tMatched) {
sPline += " Waiting for $sCompareType ${iRequiredValue} instance(s) ";
/////sPline += tStart ? "start " : "complete ";
ogPrintLine.fPrintForce(sPline + "${sWaitReason}.");
}
if (!tMatched && iCount > iRequiredValue)
throw ("instance count exceeded");
}
if (tMatched) { // all processes are ready to go
ogPrintLine.fPrintForce("Wait completed for ${iCount} instance(s) "+sWaitReason);
oCompleter.complete(true);
return;
}
iLoopCount++;
fWaitLoop();
}).catchError((oError) =>
fFatal ("fWaitForProcess", "${oError}"));
});
};
fWaitLoop();
return oCompleter.future;
}
/*
* General method to Clear a table.
*/
async.Future<bool> fClearTable(bool tShowMessage, String sTableName) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
fCheckTransactionStatus("fClearTable", true);
if (tShowMessage)
ogPrintLine.fPrintForce("Clearing ${sTableName} table");
ogDb.execute("TRUNCATE TABLE ${sTableName}").then((oResult){
fCheckTransactionStatus("fClearTable - after Truncate", false);
oCompleter.complete(true);
return;
}).catchError((oError) {
fFatal("fClearTable", "${oError}");
});
return oCompleter.future;
}
/*
* Insert a Single Row into a table using sequence number
* 'sequences' table holds last number used for Key.
*/
async.Future<bool> fInsertRowWithSequence (String sTableName,
String sSequenceKey, String sSql1) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
fCheckTransactionStatus("fInsertRowWithSequence", true);
String sNewKey; // the new key to be inserted
ogDb.execute("begin").then((_){
String sSql2 = "SELECT iLastkey FROM sequences WHERE ikey = "+
"${sSequenceKey} FOR UPDATE";
return ogDb.query(sSql2).toList();
}).then((llResult){
if (llResult.isEmpty) ///////xxxxxx test error here
throw ("fInsertRowWithSequence: row '${sSequenceKey}' for table "+
"${sTableName} is missing from 'sequences' table");
sNewKey = (llResult[0][0] +1).toString();
sSql1 = "INSERT INTO " +sTableName +sSql1.replaceFirst("?", sNewKey);
return ogDb.execute(sSql1);
}).then((int iRowsAffected){
if (iRowsAffected != 1) //////xxxxxxxxxxxxxxxxxx
throw ("fInsertRowWithSequence: Insert ${sTableName}: "+
"New Key = ${sNewKey}, rows affected Not 1 but "+
"= ${iRowsAffected}");
return ogDb.execute("UPDATE sequences SET ilastkey = "+
"${sNewKey} WHERE ikey = ${sSequenceKey}");
}).then((int iRowsAffected) {
if (iRowsAffected != 1)
throw ("fInsertRowWithSequence: Table ${sTableName}, Update "+
"Sequences: Rows Not 1 but = ${iRowsAffected}");
ogDb.execute("COMMIT").then((_) {
oCompleter.complete(true);
fCheckTransactionStatus("fInsertRowWithSequence - after COMMIT", false);
return;
});
}).catchError((oError) {
print ("fInsertRowWithSequence: Table: ${sTableName}, Error=${oError}");
oCompleter.complete(false);
});
return oCompleter.future;
}
/*
* Test the Database connection
*/
async.Future<bool> fTestConnection() {
async.Completer<bool> oCompleter = new async.Completer<bool>();
String sSql = "DROP TABLE IF EXISTS testpg001";
fExecuteSql(sSql, "Drop Table if Exists", "fTestConnection", -1)
.catchError((oError) {
oCompleter.complete(false);
})
.then((bool tResult) {
if (tResult != true && tResult != false)
fFatal("fTestConnection", "Result from fExecuteSql is invalid");
oCompleter.complete(tResult);
});
return oCompleter.future;
}
/*
* create where necessary the tables and data used by this program.
*/
async.Future<bool> fCreateTablesEtc(bool tClearMain) {
async.Completer<bool> oCompleter = new async.Completer<bool>();
ClassWrapList ollClassList = new ClassWrapList();
ogPrintLine.fPrintForce("Creating tables etc. as required");
fCheckTransactionStatus("fCreateTablesEtc", true);
// Create 'control' table first
String sSql = "CREATE TABLE IF NOT EXISTS control "+
"(iKey int Primary Key not null unique, "+
"icount1 int not null, icount2 int not null, "+
"icount3 int not null, icount4 int not null, "+
"icount5 int not null, icount6 int not null)";
fExecuteSql(sSql, "Create 'control'", "fCreateTablesEtc", -1)
.then((bool tResult) {
if (tResult != true)
fFatal("fCreateTablesEtc", "failed to create 'control' table");
fCheckTransactionStatus("fCreateTablesEtc: after tables created", true);
/*
* Insert row into 'control' table
*/
return fInsertControlRow();
})
.catchError((oError) => throw(oError))
.then((bool tResult) {
if (tResult != true)
fFatal("fCreateTablesEtc", "failed to Insert 'control' row");
// Check that required sequences rows exist //
fCheckTransactionStatus(
"fCreateTablesEtc: Prior delete from sequences", true);
// Create Main table //
sSql = "CREATE TABLE IF NOT EXISTS ${S_MAIN_TABLE} "+
"(ikey SERIAL Primary Key, "+
"sname varchar(22) not null, "+
"dbalance decimal(12,2) not null) ";
return fExecuteSql(sSql, "Create '${S_MAIN_TABLE}'", "fCreateTablesEtc", -1);
}).catchError((oError) => throw(oError))
.then((bool tResult) {
if (tResult != true)
fFatal("fCreateTablesEtc", "failed to create ${S_MAIN_TABLE}");