Most database APIs have a way of dealing with transactions – a set of operations all of which much work, and a way of rolling back if they don’t
Indeed many of the back-ends implemented here have this capability, but I haven’t yet exposed that through the abstraction layer. The main reason for this is that many of the back-ends are not actually databases, and therefore don’t have a roll back capability or the concept of transactions.
However since I had always planned to introduce rollback, I’ve implemented these kind of databases to use DriverMemory first, before committing to the back-end. This means that I can now start to implement transactions whether simulated, or using the transactional capabilities of the back-end.
Here’s how it works.
- Transactions are accessible through the normal DbAbstraction handler object, and you use an anonymous function to execute your function.
- A normal result package should be returned that can be tested for
result.handleCode < 0
meaning failure. - A transaction failure will be signaled with result.transaction.code < 0
- If a failure is detected, a rollback to before the transaction will be executed
- There will be a lock taken out for the entire transaction
- Although caching can be active in each of the individual items of the transaction as usual, there is no caching of the transaction result itself.
- The options will be used to modify the transaction behavior, or to pass additional info to your function – to be dealt with later
- Today various operations are locked to preserve consistency in multi user environments. With transactions a lock is taken out around the transaction, not for the individual operations within the transaction. For operations not enclosed in transactions, by default locking is enabled for operations that write, but not for read. However there is an option to lock both read and write operations.
Some notes on performance
- For back-ends that emulate databases (so far sheets, drive and properties), you’ll see a performance improvement for everything if you wrap multiple operations in transactions. This is because the whole thing is done in memory. The down side is that nothing else (that needs a lock) can operate on that database during the transaction.
- Aggressive locking can hurt performance when there are many simultaneous users, but you can use to guarantee consistency between writes/reads
- Operations within transactions are must faster in aggregate than separate ones. However you do lock out others for the duration of the transaction. Another side effect is that if you follow a write with a read, some databases haven’t yet properly registered by the time the read comes, and will return the wrong count. This is especially true with Orchestrate.
You can set locking when you open the database – for example.
1 2 3 4 5 6 |
var dbParameters = { "siloid": "multi", "dbid": "1yTQFdN_O2nFb9obm7AHCTmPKpf5cwAd78uNQJiCcjPk", "transactions": cDbAbstraction.dhConstants.TRANSACTIONS.ENABLED, "locking" : cDbAbstraction.dhConstants.LOCKING.AGGRESSIVE }; |
values for locking are
1 2 3 |
cDbAbstraction.dhConstants.LOCKING.AGGRESSIVE cDbAbstraction.dhConstants.LOCKING.ENABLED (default) cDbAbstraction.dhConstants.LOCKING.DISABLED |
values for transactions are
1 2 |
cDbAbstraction.dhConstants.TRANSACTIONS.ENABLED (default) cDbAbstraction.dhConstants.TRANSACTIONS.DISABLED |
If you have some code wrapped in transactions, and you disable transactions (or the driver does not yet support them), then each operations will be performed as today, but following the setting for locking.
You wrap operations in a transaction like this
1 2 3 4 5 6 7 |
var result = dbHandler.transaction ( function(db) { // your related activities }, options ); |
Example
Sheets are a particular problem, since they don’t have stable IDs (row numbers are used as IDs), and since the design principle here is not to do anything that affects the sheet’s standalone nature (anybody can change it at any time), the row number of an item can change at any time. It’s especially important to wrap operations that rely on previous operations inside a transaction. Below is a query, where the keys are used by a subsequent get. Wrapping the entire thing in a transaction ensure that some other user does not affect the row numbers in between
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 |
var r2 = handler.transaction ( function(db,options) { var result = handler.query ( { strain:strain, 'stuff.age': handler.constraints([[c.GT,25]]) },{limit:1}, 1, true ); assert ([ result.handleCode >= 0, result.data.length ===1, result.handleKeys.length ===1 ], result, "limitkeycheck1"); // testing Get var r2 = handler.get(result.handleKeys); assert ([ r2.handleCode >= 0, r2.data.length === result.data.length, r2.data.every (function(d) { return d.stuff.age > 25 ; }) ], r2, "getcheck1"); // status and result to be handled by transaction wrapper return r2; }); assert(r2.transaction.code >=0, r2, 'transaction 1'); |
another example – this time we are doing an update. It’s important that the row number IDs don’t change between the query that finds them, and the subsequent update, so wrapping them in a transaction ensures this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
var r2 = handler.transaction ( function(db,options) { var result = db.query ( { strain:strain, 'stuff.sex': 'male' },undefined,1,true); assert ([ result.handleCode >= 0, testData.filter(function(d) { return (d.stuff.sex === 'male') ; }).length === result.handleKeys.length ], result, "does male work"); var r2 = db.update( result.handleKeys, result.data.map (function(d) { d.stuff.man = d.stuff.sex === 'male'; return d; })); assert (r2.handleCode >= 0, r2, 'real update'); return r2; }); assert(r2.transaction.code >=0, r2, 'transaction 2'); |
What handler.transaction() does
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 |
/** * transaction wrapper * @param {function} transactionFunction things that need to happen inside a transaction * @param {object} options any options you want to pass on to your transaction function * @return {object} a normal result package */ this.transaction = function (transactionFunction , options) { // get id of current transaction if any var id = self.getTransactionId(); // if there was already one under way that's a bad thing if (id) { // report a transaction within a transaction as an error var results= makeResults (enums.CODE.TRANSACTION_FAILURE); results.transaction = { id: id, code: enums.CODE.OK, error:enums.ERROR.TRANSACTION_FAILURE }; results.transaction = transaction; return results; } // set up new transaction var transaction = { id: self.setTransaction(), code: enums.CODE.OK, error:'' }; // the rules // if a driver is transaction aware // it knows about locking regime of a transaction // the entire transaction will be locked // the items of the transaction are forbidden to do any locking // further, a transaction capable driver will be able to do rollback etc. // for non-aware drivers, a transaction is a non event - nothing happens, the parts of it are executed normally // if transactions are disabled, then all drivers are treated as non-transaction aware var transactionAware = driver.transactionAware && self.transactionsState() === enums.TRANSACTIONS.ENABLED; var transactionCapable = transactionAware && driver.transactionCapable; // if locking is disabled then no locking is done on the transaction var lockingEnabled = self.lockingState() !== enums.LOCKING.DISABLED && !driver.lockingBypass; var transactionLockBypass = !transactionAware || !lockingEnabled; // enclose the whole transaction var result = doGuts_ ( transactionLockBypass , "transaction:"+transaction.id , function (bypass) { // only applies to drivers that are able to do transactions if (transactionCapable) { // let the driver know it's doing a transaction driver.beginTransaction(transaction.id); // do the work try { // get the current state data, and execute the transaction contents driver.transactionData(); var r = transactionFunction (self , options); if (r.handleCode < 0 ) { localRollBack(); } else { // commit the transaction if (driver.getTransactionBox().dirty) { self.voidCache(); } var r = driver.commitTransaction(transaction.id); transaction.code = r.handleCode; transaction.error = r.handleError; } } catch (err) { localRollBack(); var r = self.makeResults(enums.CODE.TRANSACTION_FAILURE, err); } return r; } else { // the function is executed normally. // the driver should detect whether it is part of a transaction and act accordingly transaction.code = enums.CODE.TRANSACTION_INCAPABLE; transaction.error = self.getErrorText(transaction.code); // do the thing return transactionFunction (self , options); } }); // mark transaction as over result.transaction = transaction; self.clearTransaction(); return result; function localRollBack() { var r = driver.rollbackTransaction(transaction.id); transaction.code = r.handleCode < 0 ? enums.CODE.TRANSACTION_ROLLBACK_FAILED : enums.CODE.TRANSACTION_ROLLBACK; transaction.error = self.getErrorText(transaction.code); self.voidCache(); } }; |
What an enabled driver will do
self.transactionCapable = true;
self.transactionAware = true;
- detect if it is in a transaction, and not do any locking itself.
- Here is a sheet save(), instrumented for transactions.
1 2 3 |
self.save = function (obs) { return delegate.save(self.unFlatten(obs)); }; |
However sheets, properties and drive can delegate all their workload to the memory driver in a transaction, since there will be no other updates going on. This makes things much more efficient and also means that they can share the delegated code which looks like this.
What a failed transaction looks like:
Here’s a deliberate error in a transaction – I’ve spelt remove wrongly, so I want it to rollback the save operation.
1 2 3 4 5 6 7 8 9 10 |
var result = handler.transaction (function(db) { db.save([ {name:'he',ob:{a:'a1',b:'b1'}}, {name:'she',ob:{a:'ax',b:'b2'}} ]); return db.remov({name:'me'}); }); |
and the result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
{ "handleCode": -24, "handleError": "(DbAbstraction says:TRANSACTION_FAILURE) (TypeError: Cannot find function remov in object [object Object].) some transaction failure", "data": [], "handleVersion": "cDbAbstraction:2.1.1", "driverVersion": "cDriverMemory:2.1.0", "table": "multi", "dbId": "multi", "transaction": { "id": "xiui3bg5f0f", "code": -22, "error": "transaction failed, but rolled back successfully" } } |
A note on keys
As previously noted, some drivers don’t have the capability to store unique keys. In this case a unique key is generated for them temporarily. This is how the operations within a transaction can communicate with each other. This means that you can’t always rely on keys being the same inside and outside transactions. If you are dealing with keys (for example get/update), it’s always best to wrap those in a transaction. For example, with a sheet driver…
1 |
var result = handler.query({name:'john'},undefined, undefined, true); |
result.handleKeys
, will contain row numbers at that point in time – which may change at any time by other user operations, so they should not be relied on – so the following may not return the right data (it will detect it has changed and give you an error)
1 |
var r2 = handler.get (result.handleKeys) |
Whereas
1 2 3 4 |
handler.transaction ( function (db) { var result = handler.query({name:'john'},undefined, undefined, true); var r2 = handler.get (result.handleKeys); }); |
will return the correct value since the operations wont be interrupted mid flight by another update instance. Therefore, if you are using keys for database back-ends without a unique key capability, you should keep them isolated to within transactions.
DbAbstraction full code
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 |
/** * @fileOverview This is the dbabstraction data handler as described in https://ramblings.mcpher.com/database-abstraction-and-google-apps-script/ * @author <a href="mailto:bruce@mcpher.com">Bruce McPherson</a> */ /** * DbAbstraction * @constructor DbAbstraction * @param {object} driverLibrary reference to the library for the selected driver * @param {object} options - all the options as below * @param {string} tablename or silo * @param {number} [expiry] cache expiry time in seconds * @param {string} [dbid] any additional driver specific item to identify it * @param {object} [driverob] any additional driver specific object * @param {boolean} [randomsilo=false] generate a randome silo id * @param {boolean} [optout=false] opt out of analytics * @param {string} [peanut] some unique user id for analaytics * @param {string} [accesstoken] an oauth2 access token * @param {number} [disablecache=false] don't use cache at all with this one. * @param {Cache} [specificcache] a cache object to use, otherwise a public/private one belonging to cacheservice will be used * @param {string} [cachecommunity] a cache community id to restrict cache to particular groups * @param {boolean} [private=true] whether to use a private cache (not relevant if specificcache is passed) * @param {ENUM.SETTINGS.TRANSACTIONS} [transactions=ENABLED] whether to allow transactions * @param {ENUM.SETTINGS.LOCKING} [locking=ENABLED] what kind of locking to do * @param {number} waitafter the number of seconds to wait after a write operation. This should typically be zero, bur orchestrate has a non zero default */ "use strict"; function getLibraryInfo () { return { info: { name:'cDbAbstraction', version:'2.2.4', key:'MHfCjPQlweartW45xYs6hFai_d-phDA33', description:'abstraction database handler', share:'https://script.google.com/d/1Ddsb4Y-QDUqcw9Fa-rJKM3EhG2caosS9Nhch7vnQWXP7qkaMmb1wjmTl/edit?usp=sharing' }, dependencies:[ cCacheHandler.getLibraryInfo(), cUseful.getLibraryInfo(), cFlatten.getLibraryInfo(), cUAMeasure.getLibraryInfo(), cNamedLock.getLibraryInfo() ] }; } function DbAbstraction ( driverLibrary , options) { options = options || {}; // legacy - translate object to old style arguments var tableName = options.siloid; var optExpiry = options.expiry; var driver,type; var optDriverSpecific = options.dbid; var optDriverOb = options.driverob; var optRandomSilo = options.randdomsilo; var optOptOut = options.optout; var optPeanut = options.peanut; var optAccessToken = options.accesstoken; var optDisableCache = options.disablecache; var optSpecificCache = options.specificcache; var self = this; var optOut = typeof optOptOut === typeof undefined ? true : optOptOut; var peanut = optPeanut || ''; var accessToken = optAccessToken || ''; var disableCache = optDisableCache || false; var cacheCommunity = options.cachecommunity; var currentLock_ = null; var private = options.private; /** * give access to constants * @memberof DbAbstraction * @return {object} constant enums */ this.getEnums = function (){ return dhConstants; }; var enums = self.getEnums(); var locking_ = options.locking || enums.LOCKING.ENABLED; var transactions_ = options.transactions || enums.TRANSACTIONS.ENABLED; this.lockingState = function () { return locking_; }; this.transactionsState = function () { return transactions_; }; this.allDone = function () { return self.makeResults(enums.CODE.OK); } /** create the driver version * @return {string} the driver version */ self.getVersion = function () { var v = getLibraryInfo().info; return v.name + ':' + v.version; }; /** * recursive rateLimitExpBackoff() * @memberof DbAbstraction * @param {function} callBack some function to call that might return rate limit exception * @param {number} [sleepFor|enums.SETTINGS.SLEEPFOR] optional amount of time to sleep for on the first failure in missliseconds * @param {number} [maxAttempts|enums.SETTINGS.MAXATTEMPTS] optional maximum number of amounts to try * @param {number} [attempts=1] optional the attempt number of this instance - usually only used recursively and not user supplied * @return {*} results of the callback */ this.rateLimitExpBackoff = function ( callBack, sleepFor , maxAttempts, attempts ) { var self = this; return cUseful.rateLimitExpBackoff( callBack, sleepFor || self.getEnums().SETTINGS.SLEEPFOR, maxAttempts || self.getEnums().SETTINGS.MAXATTEMPTS, attempts, true ); }; /** * forces a wait after a write for options.waitafter milliseconds * the only driver i think this is needed for is orchestrate which has latency in its network * you only need this if you want to ensure that the change orchestrate has reported is committed is propogated through its infrastructure * otherwise set it to 0 - the default * @param {function} func what to do before waiting * @param {*} return whater func() returns */ this.waitAfter = function (func) { // do the thing var r = func(); // wiat a bit if necessary (only known driver this has any effect is orchestrate if (options.waitafter) { Utilities.sleep(options.waitafter); } else if (driver.WAITAFTER) { Utilities.sleep (driver.WAITAFTER); } // the function result return r; } /** * return unique string * @memberof DbAbstraction * @return {string} a unique string */ this.generateUniqueString = function () { return cUseful.generateUniqueString(self.getEnums().SETTINGS.ULENGTH); }; /** * append an aray to another */ this.arrayAppend = function (a,b) { return cUseful.arrayAppend(a,b); }; this.unFlatten = function (obs) { if (!obs) return null; var flat = new cFlatten.Flattener().setKeepDates (driver.keepDates), result; if (!Array.isArray(obs)) { result = flat.unFlatten(obs); } else { result = obs.map (function(d) { return flat.unFlatten(d); }); } return result; }; /** * flatten an array of objects/a single object * @param {Array.Object|Object} obs an array of/single unflattened objects * @param {boolean} optConstraints whether there might be constraints to preserve * @return {Array.Object|Object} an array of/single flattened objects */ this.flatten = function (obs,optConstraints) { // flatten an object if (!obs) return null; if (Array.isArray(obs)) { return obs.map(function(d) { return new cFlatten.Flattener(optConstraints ? self.getEnums().SETTINGS.CONSTRAINT : null).setKeepDates (driver.keepDates).flatten(d); }); } else { return new cFlatten.Flattener(optConstraints ? self.getEnums().SETTINGS.CONSTRAINT : null).setKeepDates (driver.keepDates).flatten(obs); } }; /** * DbAbstraction.escapeQuotes() * @memberof DbAbstraction * @param {string} str string to be escaped * @return {string} escaped string */ this.escapeQuotes = function( str ) { return cUseful.escapeQuotes(str); }; /** * check if an item is an object * @memberof DbAbstraction * @param {*} obj an item to be tested * @return {boolean} whether its an object */ this.isObject = function (obj) { return cUseful.isObject(obj); }; this.clone = function (o) { return cUseful.clone(o); }; /** * get rid of fields that are specific to a driver * @param {Array.string} drop the name of the driverfields to drop * @param {string} keyName the keyName to extract -if you want it dropped too add to drop * @param {Array.object} obs the objects to drop them from * @return {object} {[obs],[keys]} */ this.dropFields = function ( drop , keyName , obs) { // just in case its not an array if (!Array.isArray(drop)) drop = drop ? [drop] : []; if (!Array.isArray(obs)) obs = obs ? [obs] : [] ; // drop all the unwanted fields return obs.reduce(function (p,c) { // split up the object into keys and data, and drop any unwanted field. var x = Object.keys(c).reduce(function (cp,cc) { // we keep it if(drop.indexOf(cc) === -1) { cp.ob[cc] = c[cc]; } //transfer the key if (cc === keyName) { cp.key = c[cc]; } return cp; },{ob:{},key:undefined}); // add to the pile p.obs.push(x.ob); p.keys.push(x.key); return p; },{obs:[],keys:[]}); }; this.checksum = function checksum(o) { // just some random start number var c = 23; var s = (self.isObject(o) || Array.isArray(o)) ? JSON.stringify(o) : o.toString(); for (var i = 0; i < s.length; i++) { c += (s.charCodeAt(i) * (i + 1)); } return c; } var randomSilo = optRandomSilo || false; var siloId = randomSilo ? self.generateUniqueString() + tableName : tableName; var driverSpecific = optDriverSpecific; var driverOb = optDriverOb || null; var expiry = optExpiry || enums.SETTINGS.CACHEEXPIRY; this.getLockName = function (optType) { return {type:optType || type,key:driverSpecific,id:siloId}; }; this.lock = function (optType) { return new cNamedLock.NamedLock(enums.SETTINGS.PROTECTEXPIRY).setKey(self.getLockName(optType)); }; /** * select and open handler for the backend driver * @memberof DbAbstraction * @return {object} driver for the database - normally used only inside this class */ this.setDriver = function () { try { return driverLibrary.createDriver(self,siloId,driverSpecific,driverOb, accessToken,options); } catch(err) { throw err + '-an unknown database type'; } }; var driver = self.setDriver(); var type = driver.getType(); var cacheSilo = 's'+siloId+'t'+type+'d'+driverSpecific; var cacheHandler = new cCacheHandler.CacheHandler(expiry,cacheSilo,private,disableCache,optSpecificCache,cacheCommunity); var cacheVoid = new cCacheHandler.CacheHandler(expiry*2,cacheSilo,false,false,null,'void'); var transactionId_; /** analytics measurement */ var ua,uap; if (!optOut) { uap = PropertiesService.getScriptProperties().getProperty(enums.SETTINGS.UAKEY); if (uap) { var uaProperties = JSON.parse(uap); ua = new cUAMeasure.UAMeasure (uaProperties.uaCode, uaProperties.property, peanut, optOut , self.getVersion()); } } /** * return the back end handler * @memberof DbAbstraction * @return {object} driver for the database */ this.getDriver = function () { return driver; }; /** * DbAbstraction.getTableName() * @memberof DbAbstraction * @return {string} table name or silo */ this.getTableName = function () { return driver.getTableName(); }; this.getDBName = function () { for (var k in enums.DB) { if (type === enums.DB[k]) { return k; } } throw ('DB-' + type + ' error code unknown:programming error-'); }; this.getTransactionId = function () { return transactionId_; }; this.clearTransaction = function () { transactionId_ = null; }; this.setTransaction = function () { transactionId_ = cUseful.generateUniqueString(3); return self.getTransactionId(); }; this.rollBack = function () { // doesnt do anything yet return enums.CODE.TRANSACTION_ROLLBACK_FAILED; } /** * organize given constraints * @memberof DbAbstraction * @param {object|object[]} constraints constratints to be organized * @return {object} an object containing all the constraints */ this.constraints = function (constraints) { if (!Array.isArray(constraints)) constraints = [constraints]; if (!constraints.length) return null; if (!Array.isArray(constraints[0])) constraints = [constraints]; var e={}; e[enums.SETTINGS.CONSTRAINT] = constraints.map(function(c){ if (!c[0]) throw ('unknown constraint:' + JSON.stringify(c)); return {constraint:c[0],value:c[1]}; }); return e; }; this.getErrorCode = function (hCode,messageText) { var code; for (var k in enums.CODE) { if (hCode === enums.CODE[k]) { code =k; break; } } if (typeof code==='undefined' ) { throw ('code' + hCode + ' error code unknown:programming error-' + (messageText || '')); } return code; }; this.getErrorText = function(hCode) { return enums.ERROR[self.getErrorCode(hCode)]; } /** * DbAbstraction.makeResults() * @memberof DbAbstraction * @param {dhConstants.CODE} handleCode the error code 0 = good, -ve = bad, +ve = warning * @param {string} messageText any additional error text to add to the handleError * @param {object} result the result code returned from the driver * @return {object} results */ this.makeResults = function (handleCode,messageText,result,driverIds,handleKeys) { var handleError; var code = self.getErrorCode(handleCode,messageText); handleError = (messageText ? " (" + messageText + ") " : '') + enums.ERROR[code]; // check that the results are valid if (handleCode === enums.CODE.OK && result && result.error) { handleError += "(" + enums.ERROR.RESULT + ")"; handleCode = enums.CODE.RESULT; } if (handleError) { handleError = '(DbAbstraction says:'+code+') '+handleError; } var r = (result === null || typeof result === 'undefined') ? [] : result; var ret = {handleCode:handleCode, handleError:handleError,data:r, handleVersion:self.getVersion()}; if (driver) { ret.driverVersion = driver.getVersion(); ret.table = driver.getTableName(); ret.dbId = driver.getDbId(); ret.keyProperty = driver.getKeyProperty ? driver.getKeyProperty() : 'key'; } else { ret.driverVersion = 'unknown driver version'; } if (handleKeys) { ret.handleKeys = handleKeys; } if (driverIds) { ret.driverIds = driverIds; } return ret; }; this.uaPage = function (action) { return 'db'+ '_' + action +'_' + driver.getVersion(); }; /** * DbAbstraction.remove() * @memberof DbAbstraction * @param {object} [queryOb] some query object * @param {object} [queryParams] additional query parameters (if available) * @param {boolean} [noCache=0] whether to suppress cache * @return {object} results from selected handler */ this.remove = function (queryOb,queryParams) { return self.uaWrap ('remove', function () { self.voidCache(); return driver.remove(queryOb,queryParams); }); }; this.uaWrap = function (what, func) { if (ua) { ua.postAppView(self.uaPage (what)); } var result = func(); if (ua) { ua.postAppKill(); } return result; }; /** * DbAbstraction.removeByIds() * @memberof DbAbstraction * @param {Array.string} ids list of handleKey ids to remove * @return {object} results from selected handler */ this.removeByIds = function (ids) { if (!ids) { return self.makeResults(enums.CODE.NO_ACTION,'list of ids not present in removeByIds'); } return self.uaWrap ('removeByIds', function () { if(!Array.isArray(ids)) ids = [ids]; self.voidCache(); return driver.removeByIds(ids); }); }; /** * DbAbstraction.save() * @memberof DbAbstraction * @param {object[]} obs array of objects to write * @return {object} results from selected handler */ this.save = function (obs) { return self.uaWrap ('save', function () { self.voidCache(); var obArray = Array.isArray(obs) ? obs : [obs]; return driver.save(obArray); }); }; /** * should be called when a databse update is done * any cache entries with an earlier timestamp are not valid * return void */ this.voidCache = function () { cacheVoid.putCache (self.getCob ([], 'v'),"v"); }; /** * call with a cache object * if its timestamp is earlier that the last update for this silo it will return null * @param {object} cob * @return {object | null } the arg or null if invalid */ this.usableCache = function (cob) { if (cob && cob.hasOwnProperty('cacheProperties')) { // need to get the cob associated with the silo var siloCob = cacheVoid.getCache ("v"); return siloCob && siloCob.cacheProperties.timeStamp >= cob.cacheProperties.timeStamp ? null : cob; } else { return cob; } }; /** * create a timestamped cache object * @param {obect} data the data * @param {string} operation the operation * @return {object} the cob */ this.getCob = function (data, operation) { return { data:data, cacheProperties: { timeStamp:new Date().getTime(), operation:operation, siloKey:cacheSilo } }; } this.cobMessage = function (cob) { return cob && cob.hasOwnProperty('cacheProperties') ? JSON.stringify(cob.cacheProperties) + " (was written at " + Utilities.formatDate(new Date(cob.cacheProperties.timeStamp),"GMT","yyyy-MM-dd HH:mm:ss.SSS") + ") " : ""; }; this.cobbery = function (queryOb, queryParams, noCache , operation) { var cob,cached; //we dont use cache if in a transaction if (!self.getTransactionId()) { // if cache is noy disabled if (!noCache && ! disableCache) { // make sure that cache is still viable and get dataif any cob = self.usableCache(cacheHandler.getCache(queryOb,queryParams,operation)); cached = cob && cob.hasOwnProperty('cacheProperties') ? cob.data : cob; } } // will return a results package or null return cob ? self.makeResults(enums.CODE.CACHE, self.cobMessage(cob), cached) : null; }; /** * DbAbstraction.count() * @memberof DbAbstraction * @param {object} [queryOb] some query object * @param {object} [queryParams] additional query parameters (if available) * @param {boolean} [noCache=0] whether to suppress cache * @return {object} results from selected handler */ this.count = function (queryOb,queryParams,noCache) { return self.uaWrap ('count', function () { var cob = self.cobbery (queryOb,queryParams,noCache,"c"); if (cob) { return cob; } else { var result = driver.count(queryOb,queryParams,noCache); if (result.handleCode <0) { self.voidCache(); } else { cacheHandler.putCache (self.getCob(result.data,"c"),queryOb,queryParams,"c"); } return result; } }); }; /** * DbAbstraction.query() * @memberof DbAbstraction * @param {object} [queryOb] some query object * @param {object} [queryParams] additional query parameters (if available) * @param {boolean} [noCache=0] whether to suppress cache * @param {boolean} [optKeepIds=false] whether or not to keep driver specifc ids in the results * @return {object} results from selected handler */ this.query = function (queryOb,queryParams,noCache,optKeepIds) { var cached,result; var keepIds = (typeof optKeepIds === 'undefined' ? enums.SETTINGS.KEEPIDS : optKeepIds); var cob; // we dont do caching if we need the ids if (!optKeepIds) { cob = self.cobbery (queryOb,queryParams,noCache,"q"); } if (cob) { return cob; } else { return self.uaWrap ('query', function () { // if queryOb is an array then we are doing an OR var doingOR = Array.isArray(queryOb); if (doingOR) { if (!Array.isArray(queryParams)) { queryParams = [queryParams]; } var datas = [],keys =[],dIds =[]; code = enums.CODE.OK; err = ''; queryOb.forEach (function (q,i) { var t = driver.query(q,queryParams.length === 1 ? queryParams[0] : queryParams[i],true); if (t.handleCode < 0) { code = t.handleCode; err = t.handleError; } else { // concatenate results t.data.forEach (function (d,j) { if( !keys.some(function(k) { return k === t.handleKeys[j]; })) { keys.push(t.handleKeys[j]); dIds.push(t.driverIds[j]); datas.push(d); } }); } }); result = self.makeResults(code,err,datas,keepIds ? dIds :null,keepIds ? keys:null); } else { result = driver.query(queryOb,queryParams,keepIds); } if (result.handleCode <0) { self.voidCache(); } else { cacheHandler.putCache (self.getCob(result.data,"q"),queryOb,queryParams,"q"); } return result; }); } }; /** * DbAbstraction.get() * @memberof DbAbstraction * @param {string} key some unqiue key as returned by handleKeys * @param {boolean} [noCache=0] whether to suppress cache * @param {boolean} [keepIds=false] whether or not to keep driver specifc ids in the results * @return {object} results from selected handler */ this.get = function (key,noCache,optKeepIds) { return self.uaWrap ('get', function () { var cached; var keepIds = (typeof optKeepIds === 'undefined' ? enums.SETTINGS.KEEPIDS : optKeepIds); var cString = "g"+keepIds; var cob; if(!optKeepIds) { cob = self.cobbery (key,undefined,noCache,cString); } if (cob) { return cob; } else { var result = driver.get(key,keepIds); if (result.handleCode <0) { self.voidCache(); } else { cacheHandler.putCache (self.getCob(result.data,cString),key,undefined,cString); } return result; } }); }; /** * DbAbstraction.update() * @memberof DbAbstraction * @param {string} key some unqiue key as returned by handleKeys * @param {object} ob what to update it to * @return {object} results from selected handler */ this.update = function (key,ob) { return self.uaWrap ('update', function () { self.voidCache(); return driver.update(key,ob); }); }; /** * DbAbstraction.getDriveHandle() * @memberof DbAbstraction * @return {object} the driver handle */ this.getDriveHandle = function () { return driver.getDriveHandle() ; }; /** * DbAbstraction.isHappy() * @memberof DbAbstraction * @return {boolean} whether the driver is ready to use */ this.isHappy = function () { return (driver && self.getDriveHandle() && driver.getTableName() && type ) ? true : false; }; // utility functions for use by driver this.makeUseParams = function(paramsData) { // set a more convenient params object return paramsData.reduce (function (p,c) { p[c.param] = c; return p; },{skip:{skip:0},limit:{limit:0},sort:null}); }; /** * DbAbstraction.getQueryParams() * @memberof DbAbstraction * @param {object} [queryParams] additional query parameters (if available) * @return {object} results the parameters sorted out */ this.getQueryParams = function(queryParams) { var result =[], handleError='', handleCode=enums.CODE.OK, order =['sort','skip','limit']; if (queryParams) { // need to ensure we do sort before limit result = Object.keys(queryParams).sort (function (a,b) { var ka = order.indexOf(a); var kb = order.indexOf(b); // deal with unknown parameters if (kb === -1) return 1; if (ka === -1) return -1; // sort according to order in order array return ka < kb ? -1 : (ka === kb ? 0 : 1); }) .map (function(q) { if (q==='sort') { var sortDescending = (queryParams[q].slice(0,1) === '-'); var sortKey = sortDescending ? queryParams[q].slice(1) : queryParams[q]; return {param:q,sortKey:sortKey,sortDescending:sortDescending,value:queryParams[q]}; } else { var v = parseInt(queryParams[q],10); if (q==='limit' || q==='skip') { if (!isNaN(v)) { return q === 'limit' ? {param:q,limit:v,value:queryParams[q]} : {param:q,skip:v,value:queryParams[q]}; } else { handleError = 'Invalid vaue for ' + q + ':' + queryParams[q]; handleCode = enums.CODE.PROPERTY; return null; } } else { // this could be some custom parameter for the driver i cant validate return {param:q,value:queryParams[q]}; } } }); } return self.makeResults(handleCode,handleError,result); }; /** * DbAbstraction.makeQuote() * @memberof DbAbstraction * @param {*} item quote a string if its a string * @param {string} [optForce=false] if this is supposed to be a string, convert it to as tring and quote it * @param {string} [optTheQuote='] the kind of quote to use * @return {object} escaped string */ this.makeQuote = function (item,optForce,optTheQuote) { // add quotes if necessary var theQuote = optTheQuote || "'"; var fType = optForce ? optForce.toUpperCase() : ''; if ( ( fType !== "NUMBER") || (!fType && (typeof item === "string" || cUseful.isDateObject(item))) ) { return theQuote + item.toString().replace(theQuote, "\\" + theQuote ) + theQuote; } else { return isNaN(item) && optForce && optForce.toUpperCase() === "NUMBER" ? theQuote + theQuote : item; } }; /** * DbAbstraction.cleanPropertyName() * @memberof DbAbstraction * @param {string} name tidy of this name to contain good property names * @return {object} cleaner string */ this.cleanPropertyName = function (name) { var a,b,r=/[^a-zA-Z_#@0-9\.]/; if (name) { a = name.slice(0,1); if (/[^a-zA-Z_]/.test(a)) { name = "_" + name; } name = name.replace ( r , "_"); if (name.length > enums.SETTINGS.MAXPROPERTYNAME) name = name.slice(0,enums.SETTINGS.MAXPROPERTYNAME); } return name; }; /** * DbAbstraction.renameProperty() * @memberof DbAbstraction * @param {object} ob object containing the property to be renamed * @param {string} fromProp the name of property to be renamed * @param {string} toProp what to rename the property as * @return {object} the object */ this.renameProperty = function(ob,fromProp, toProp) { ob[toProp] = ob[fromProp]; delete ob[fromProp]; return ob; }; /** * DbAbstraction.cleanPropertyNames() * @memberof DbAbstraction * @param {object} ob object containing the properties to be checked and cleaned up * @return {object} the object */ this.cleanPropertyNames = function (ob) { if (ob) { var ks = []; // because the indices will get touched... for (var k in ob) { ks.push(k); } ks.forEach(function(k) { // recurse for children if (typeof ob[k] === 'object' ) { self.cleanPropertyNames (ob[k]); } if (!Array.isArray(ob)) { var a = self.cleanPropertyName(k); var idx = 0,t=''; // avoid duplicate property names if (a !== k) { while (ob.hasOwnProperty(a+t)) { t = a + "_" + idx; } self.renameProperty (ob , k , a+t); } } }); } return ob; }; /** * DbAbstraction.processParams() * @memberof DbAbstraction * @param {object} [queryParams] apply these parameters * @param {object} inputData to this data * @return {object} a results object containing the status and the modified data */ this.processParams = function (queryParams,inputData) { var handleError='',handleCode=enums.CODE.OK,hk =[]; // need to remember the index var sData = inputData.map (function (d,i) { return {d:d,index:i}; }); var params = self.getQueryParams(queryParams); if (params.handleCode === enums.CODE.OK) { // we have an array of good query params if(params.data.length) { params.data.forEach( function (e) { if(e.param === 'sort') { sData.sort (function (a,b) { var ad = a.d.data ? a.d.data : a.d; var bd = b.d.data ? b.d.data : b.d; var as = ad[e.sortKey],bs = bd[e.sortKey]; return (as < bs ? -1 : ( as===bs ? 0 : 1)) * (e.sortDescending ? -1 : 1); }); } else if (e.param === 'limit') { sData = sData.slice(0,e.limit); } else if (e.param ==='skip') { sData = sData.slice (e.skip); } else { handleError = e.param; handleCode = enums.CODE.PARAMNOTIMPLEMENTED; } }); } } else { handleError = params.handleError; handleCode = params.handleCode; } return self.makeResults(handleCode,handleError,sData.map(function(d) { return d.d; }),undefined,sData.map(function(d) { return d.index; })); }; /** * DbAbstraction.processFilters() - can be used to post process data if the driver is unable to handle constraints or filters * @memberof DbAbstraction * @param {object} [queryOb] apply these constraints and query * @param {object} inputData to this data * @return {object} a results object containing the status and the modified data */ this.processFilters = function (queryOb,inputData) { var handleError='',handleCode=enums.CODE.OK; var sData = inputData.map (function (d,i) { return {d:d,index:i}; }); if (queryOb) { var fob = new cFlatten.Flattener(enums.SETTINGS.CONSTRAINT).setKeepDates (driver.keepDates).flatten(queryOb); var f = new cFlatten.Flattener().setKeepDates (driver.keepDates); sData = sData.filter (function (row,i) { var rd = f.flatten(row.d.data ? row.d.data : row.d); return Object.keys(fob).every(function(k) { return self.constraintFilter(rd,fob,k); }); }); } return self.makeResults(handleCode,handleError,sData.map(function(d) { return d.d; }),undefined,sData.map(function(d) { return d.index; })); }; /** * DbAbstraction.processFilters() - can be used to post process data if the driver is unable to handle constraints * @memberof DbAbstraction * @param {object} rd flattened data row * @param {object} fob a flattened object * @param {object} k the index of the query item to process * @return {boolean} whether this row should be included in the result */ this.constraintFilter = function (rd,qob,k) { if (qob[k].hasOwnProperty(enums.SETTINGS.CONSTRAINT)) { return qob[k][enums.SETTINGS.CONSTRAINT].every ( function (c) { var good= ( c.constraint === enums.CONSTRAINTS.LT && rd[k] < c.value ) || ( c.constraint === enums.CONSTRAINTS.LTE && rd[k] <= c.value ) || ( c.constraint === enums.CONSTRAINTS.GT && rd[k] > c.value ) || ( c.constraint === enums.CONSTRAINTS.GTE && rd[k] >= c.value ) || ( c.constraint === enums.CONSTRAINTS.NE && rd[k] !== c.value ) || ( c.constraint === enums.CONSTRAINTS.EQ && rd[k] === c.value ) || ( c.constraint === enums.CONSTRAINTS.IN && c.value.indexOf(rd[k]) >= 0) || ( c.constraint === enums.CONSTRAINTS.NIN && c.value.indexOf(rd[k]) < 0 ) ; return good; }); } else if (rd.hasOwnProperty(k)) { return rd[k] === qob[k]; } else { handleError = k; handleCode = enums.CODE.PROPERTY; return false; } }; /** * checks that the transaction matches the one stored * @param {string} id transaction id * @return {boolean} whether id matches */ self.isTransaction = function (id) { return driver.getTransactionBox && driver.getTransactionBox() && driver.getTransactionBox().id === id ; }; self.inTransaction = function () { return self.isTransaction( self.getTransactionId()); }; /** * transaction wrapper * @param {function} transactionFunction things that need to happen inside a transaction * @param {object} options any options you want to pass on to your transaction function * @return {object} a normal result package */ this.transaction = function (transactionFunction , options) { // get id of current transaction if any var id = self.getTransactionId(); // if there was already one under way that's a bad thing if (id) { // report a transaction within a transaction as an error var results= makeResults (enums.CODE.TRANSACTION_FAILURE); results.transaction = { id: id, code: enums.CODE.OK, error:enums.ERROR.TRANSACTION_FAILURE }; results.transaction = transaction; return results; } // set up new transaction var transaction = { id: self.setTransaction(), code: enums.CODE.OK, error:'' }; // the rules // if a driver is transaction aware // it knows about locking regime of a transaction // the entire transaction will be locked // the items of the transaction are forbidden to do any locking // further, a transaction capable driver will be able to do rollback etc. // for non-aware drivers, a transaction is a non event - nothing happens, the parts of it are executed normally // if transactions are disabled, then all drivers are treated as non-transaction aware var transactionAware = driver.transactionAware && self.transactionsState() === enums.TRANSACTIONS.ENABLED; var transactionCapable = transactionAware && driver.transactionCapable; // if locking is disabled then no locking is done on the transaction var lockingEnabled = self.lockingState() !== enums.LOCKING.DISABLED && !driver.lockingBypass; var transactionLockBypass = !transactionAware || !lockingEnabled; // enclose the whole transaction var result = doGuts_ ( transactionLockBypass , "transaction:"+transaction.id , function (bypass) { // only applies to drivers that are able to do transactions if (transactionCapable) { // let the driver know it's doing a transaction driver.beginTransaction(transaction.id); // do the work try { // get the current state data, and execute the transaction contents driver.transactionData(); var r = transactionFunction (self , options); if (r.handleCode < 0 ) { localRollBack(); } else { // commit the transaction if (driver.getTransactionBox().dirty) { self.voidCache(); } var r = driver.commitTransaction(transaction.id); transaction.code = r.handleCode; transaction.error = r.handleError; } } catch (err) { localRollBack(); var r = self.makeResults(enums.CODE.TRANSACTION_FAILURE, err); } return r; } else { // the function is executed normally. // the driver should detect whether it is part of a transaction and act accordingly transaction.code = enums.CODE.TRANSACTION_INCAPABLE; transaction.error = self.getErrorText(transaction.code); // do the thing return transactionFunction (self , options); } }); // mark transaction as over result.transaction = transaction; self.clearTransaction(); return result; function localRollBack() { var r = driver.rollbackTransaction(transaction.id); transaction.code = r.handleCode < 0 ? enums.CODE.TRANSACTION_ROLLBACK_FAILED : enums.CODE.TRANSACTION_ROLLBACK; transaction.error = self.getErrorText(transaction.code); self.voidCache(); } }; self.getCurrentLock = function () { return currentLock_; }; /** * convenience function to apply locking on a write type operation * @param {string} what comment for locking debuging * @param {function} func what to wrap if not in transaction * @param {function} transactionFunc to wrap * @return {object} whatever func() returns */ self.readGuts = function (what, func, transactionFunc) { return doGuts_ (self.lockingState() !== enums.LOCKING.AGGRESSIVE , 'aggressive ' + what , func, transactionFunc) ; }; /** * convenience function to apply locking on a write type operation * @param {string} what comment for locking debuging * @param {function} func what to wrap if not in transaction * @param {function} transactionFunc to wrap * @return {object} whatever func() returns */ self.writeGuts = function (what, func, transactionFunc) { return self.waitAfter( function () { return doGuts_ (self.lockingState() === enums.LOCKING.DISABLED , what , func , transactionFunc) ; }); }; function doGuts_ (bypass , what , func, transactionFunc ) { if (self.getCurrentLock()) { return transactionFunc ? transactionFunc(bypass) : func(bypass); } else { if (bypass) { // been told not to bother return func(bypass); } else { // need to get a lock and execute the function return self.lock().protect (what, function (lock) { // save the allocated lock to avoid deadlocking inside the lamda currentLock_ = lock; // run the function var result = func(bypass) ; // all is good lock can be forgotten currentLock_ = null; return result; }).result; } } } return self; }; |
For more on this see Parallel processing in Apps Script and Database abstraction with google apps script