@blazedpath/commons 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/README.md +3 -0
  2. package/blz-base/health/index.js +215 -0
  3. package/blz-base/index.js +1466 -0
  4. package/blz-cache/LruCache.js +44 -0
  5. package/blz-cache/index.js +29 -0
  6. package/blz-config/index.js +434 -0
  7. package/blz-core/index.js +364 -0
  8. package/blz-cryptography/index.js +54 -0
  9. package/blz-datetimes/index.js +356 -0
  10. package/blz-file/example.dat +2545 -0
  11. package/blz-file/fileService.js +205 -0
  12. package/blz-file/index.js +94 -0
  13. package/blz-file/index.test.js +31 -0
  14. package/blz-file/lab.js +33 -0
  15. package/blz-hazelcast/index.js +189 -0
  16. package/blz-hazelcast/lib/credentials.js +25 -0
  17. package/blz-hazelcast/lib/credentialsFactory.js +12 -0
  18. package/blz-hazelcast/lib/hazelcastCache.js +234 -0
  19. package/blz-iterable/index.js +446 -0
  20. package/blz-json-schema/index.js +11 -0
  21. package/blz-jwt/index.js +121 -0
  22. package/blz-kafka/index.js +522 -0
  23. package/blz-math/index.js +131 -0
  24. package/blz-mongodb/index.js +326 -0
  25. package/blz-rds/__test__/scape.test.js +58 -0
  26. package/blz-rds/blz-rds-executor.js +578 -0
  27. package/blz-rds/blz-rds-helper.js +310 -0
  28. package/blz-rds/commands/core/add.js +13 -0
  29. package/blz-rds/commands/core/and.js +18 -0
  30. package/blz-rds/commands/core/asc.js +10 -0
  31. package/blz-rds/commands/core/avg.js +10 -0
  32. package/blz-rds/commands/core/column-ref.js +8 -0
  33. package/blz-rds/commands/core/count-distinct.js +10 -0
  34. package/blz-rds/commands/core/count.js +10 -0
  35. package/blz-rds/commands/core/decimal.js +8 -0
  36. package/blz-rds/commands/core/desc.js +10 -0
  37. package/blz-rds/commands/core/distinct.js +10 -0
  38. package/blz-rds/commands/core/divide.js +11 -0
  39. package/blz-rds/commands/core/embedded-exists.js +17 -0
  40. package/blz-rds/commands/core/embedded-select.js +17 -0
  41. package/blz-rds/commands/core/equals.js +9 -0
  42. package/blz-rds/commands/core/false.js +8 -0
  43. package/blz-rds/commands/core/greater-or-equal.js +9 -0
  44. package/blz-rds/commands/core/greater.js +9 -0
  45. package/blz-rds/commands/core/in.js +9 -0
  46. package/blz-rds/commands/core/integer.js +8 -0
  47. package/blz-rds/commands/core/is-not-null.js +11 -0
  48. package/blz-rds/commands/core/is-null-or-value.js +10 -0
  49. package/blz-rds/commands/core/is-null.js +11 -0
  50. package/blz-rds/commands/core/less-or-equal.js +9 -0
  51. package/blz-rds/commands/core/less-unary.js +12 -0
  52. package/blz-rds/commands/core/less.js +9 -0
  53. package/blz-rds/commands/core/like.js +12 -0
  54. package/blz-rds/commands/core/max.js +10 -0
  55. package/blz-rds/commands/core/min.js +10 -0
  56. package/blz-rds/commands/core/multiply.js +13 -0
  57. package/blz-rds/commands/core/not-equals.js +9 -0
  58. package/blz-rds/commands/core/not-in.js +9 -0
  59. package/blz-rds/commands/core/not.js +13 -0
  60. package/blz-rds/commands/core/null.js +8 -0
  61. package/blz-rds/commands/core/nvl.js +11 -0
  62. package/blz-rds/commands/core/or.js +13 -0
  63. package/blz-rds/commands/core/parameter.js +34 -0
  64. package/blz-rds/commands/core/remainder.js +16 -0
  65. package/blz-rds/commands/core/string.js +8 -0
  66. package/blz-rds/commands/core/subtract.js +13 -0
  67. package/blz-rds/commands/core/sum.js +10 -0
  68. package/blz-rds/commands/core/true.js +8 -0
  69. package/blz-rds/commands/core/tuple.js +13 -0
  70. package/blz-rds/commands/datetimes/add-days.js +11 -0
  71. package/blz-rds/commands/datetimes/add-hours.js +11 -0
  72. package/blz-rds/commands/datetimes/add-milliseconds.js +11 -0
  73. package/blz-rds/commands/datetimes/add-minutes.js +11 -0
  74. package/blz-rds/commands/datetimes/add-months.js +11 -0
  75. package/blz-rds/commands/datetimes/add-seconds.js +11 -0
  76. package/blz-rds/commands/datetimes/add-years.js +11 -0
  77. package/blz-rds/commands/datetimes/date-diff.js +11 -0
  78. package/blz-rds/commands/datetimes/date.js +12 -0
  79. package/blz-rds/commands/datetimes/datetime-diff.js +11 -0
  80. package/blz-rds/commands/datetimes/datetime.js +15 -0
  81. package/blz-rds/commands/datetimes/day.js +10 -0
  82. package/blz-rds/commands/datetimes/hour.js +10 -0
  83. package/blz-rds/commands/datetimes/millisecond.js +10 -0
  84. package/blz-rds/commands/datetimes/minute.js +10 -0
  85. package/blz-rds/commands/datetimes/month-text.js +10 -0
  86. package/blz-rds/commands/datetimes/month.js +10 -0
  87. package/blz-rds/commands/datetimes/now.js +9 -0
  88. package/blz-rds/commands/datetimes/second.js +10 -0
  89. package/blz-rds/commands/datetimes/subtract-days.js +11 -0
  90. package/blz-rds/commands/datetimes/subtract-hours.js +11 -0
  91. package/blz-rds/commands/datetimes/subtract-milliseconds.js +11 -0
  92. package/blz-rds/commands/datetimes/subtract-minutes.js +11 -0
  93. package/blz-rds/commands/datetimes/subtract-seconds.js +11 -0
  94. package/blz-rds/commands/datetimes/time-diff.js +11 -0
  95. package/blz-rds/commands/datetimes/time.js +13 -0
  96. package/blz-rds/commands/datetimes/today.js +9 -0
  97. package/blz-rds/commands/datetimes/week-day-text.js +10 -0
  98. package/blz-rds/commands/datetimes/week-day.js +10 -0
  99. package/blz-rds/commands/datetimes/week.js +10 -0
  100. package/blz-rds/commands/datetimes/year.js +10 -0
  101. package/blz-rds/commands/math/abs.js +10 -0
  102. package/blz-rds/commands/math/acos.js +10 -0
  103. package/blz-rds/commands/math/asin.js +10 -0
  104. package/blz-rds/commands/math/atan.js +10 -0
  105. package/blz-rds/commands/math/atan2.js +11 -0
  106. package/blz-rds/commands/math/ceil.js +10 -0
  107. package/blz-rds/commands/math/cos.js +10 -0
  108. package/blz-rds/commands/math/cosh.js +10 -0
  109. package/blz-rds/commands/math/exp.js +10 -0
  110. package/blz-rds/commands/math/floor.js +10 -0
  111. package/blz-rds/commands/math/log.js +18 -0
  112. package/blz-rds/commands/math/log10.js +10 -0
  113. package/blz-rds/commands/math/pow.js +11 -0
  114. package/blz-rds/commands/math/random.js +9 -0
  115. package/blz-rds/commands/math/round.js +18 -0
  116. package/blz-rds/commands/math/sign.js +10 -0
  117. package/blz-rds/commands/math/sin.js +10 -0
  118. package/blz-rds/commands/math/sinh.js +10 -0
  119. package/blz-rds/commands/math/sqrt.js +10 -0
  120. package/blz-rds/commands/math/tan.js +10 -0
  121. package/blz-rds/commands/math/tanh.js +10 -0
  122. package/blz-rds/commands/math/trunc.js +18 -0
  123. package/blz-rds/commands/strings/concat.js +20 -0
  124. package/blz-rds/commands/strings/contains.js +12 -0
  125. package/blz-rds/commands/strings/ends-with.js +12 -0
  126. package/blz-rds/commands/strings/index-of.js +11 -0
  127. package/blz-rds/commands/strings/is-null-or-empty.js +11 -0
  128. package/blz-rds/commands/strings/is-null-or-white-space.js +11 -0
  129. package/blz-rds/commands/strings/join.js +22 -0
  130. package/blz-rds/commands/strings/last-index-of.js +11 -0
  131. package/blz-rds/commands/strings/length.js +10 -0
  132. package/blz-rds/commands/strings/pad-left.js +20 -0
  133. package/blz-rds/commands/strings/pad-right.js +20 -0
  134. package/blz-rds/commands/strings/replace.js +12 -0
  135. package/blz-rds/commands/strings/starts-with.js +12 -0
  136. package/blz-rds/commands/strings/substring.js +12 -0
  137. package/blz-rds/commands/strings/to-lower.js +10 -0
  138. package/blz-rds/commands/strings/to-upper.js +10 -0
  139. package/blz-rds/commands/strings/trim-end.js +10 -0
  140. package/blz-rds/commands/strings/trim-start.js +10 -0
  141. package/blz-rds/commands/strings/trim.js +10 -0
  142. package/blz-rds/index.js +744 -0
  143. package/blz-rds-mysql/base.js +857 -0
  144. package/blz-rds-mysql/connection-manager.js +129 -0
  145. package/blz-rds-mysql/execute-bulk-insert.js +35 -0
  146. package/blz-rds-mysql/execute-bulk-merge.js +45 -0
  147. package/blz-rds-mysql/execute-non-query.js +34 -0
  148. package/blz-rds-mysql/execute-query.js +50 -0
  149. package/blz-rds-mysql/index.js +41 -0
  150. package/blz-rds-mysql/stored-procedure.js +207 -0
  151. package/blz-rds-mysql/syntaxis.json +114 -0
  152. package/blz-rds-mysqlx/base.js +846 -0
  153. package/blz-rds-mysqlx/connection-manager.js +141 -0
  154. package/blz-rds-mysqlx/execute-bulk-insert.js +35 -0
  155. package/blz-rds-mysqlx/execute-bulk-merge.js +45 -0
  156. package/blz-rds-mysqlx/execute-non-query.js +29 -0
  157. package/blz-rds-mysqlx/execute-query.js +39 -0
  158. package/blz-rds-mysqlx/index.js +41 -0
  159. package/blz-rds-mysqlx/stored-procedure.js +179 -0
  160. package/blz-rds-mysqlx/syntaxis.json +105 -0
  161. package/blz-rds-oracle/index.js +540 -0
  162. package/blz-rds-oracle/syntaxis.json +112 -0
  163. package/blz-rds-postgres/base.js +861 -0
  164. package/blz-rds-postgres/connection-manager.js +225 -0
  165. package/blz-rds-postgres/execute-bulk-insert.js +81 -0
  166. package/blz-rds-postgres/execute-bulk-merge.js +93 -0
  167. package/blz-rds-postgres/execute-non-query.js +23 -0
  168. package/blz-rds-postgres/execute-query.js +37 -0
  169. package/blz-rds-postgres/index.js +41 -0
  170. package/blz-rds-postgres/result-set.js +51 -0
  171. package/blz-rds-postgres/stored-procedure.js +116 -0
  172. package/blz-rds-postgres/syntaxis.json +114 -0
  173. package/blz-redis/index.js +217 -0
  174. package/blz-redis/lib/redisCache.js +265 -0
  175. package/blz-regex/index.js +25 -0
  176. package/blz-security/.eslintrc.js +15 -0
  177. package/blz-security/__test__/AuthorizationKpn.yaml +1043 -0
  178. package/blz-security/__test__/FinancingSetting.yaml +177 -0
  179. package/blz-security/__test__/KpnConfigPortal.yaml +330 -0
  180. package/blz-security/__test__/OrderManagement.yaml +5190 -0
  181. package/blz-security/__test__/Security.yaml +128 -0
  182. package/blz-security/__test__/autorization.test.js +105 -0
  183. package/blz-security/__test__/orderManagement.test.js +26 -0
  184. package/blz-security/__test__/secureUrl.test.js +79 -0
  185. package/blz-security/__test__/solveMergeRule.test.js +109 -0
  186. package/blz-security/__test__/sqlInjectionGuard.test.js +203 -0
  187. package/blz-security/__test__/xssGuard.test.js +204 -0
  188. package/blz-security/authorizationService.js +536 -0
  189. package/blz-security/config/global.js +8 -0
  190. package/blz-security/config/welcome +8 -0
  191. package/blz-security/doc/README.md +75 -0
  192. package/blz-security/filescanner/index.js +46 -0
  193. package/blz-security/helpers/consts.js +229 -0
  194. package/blz-security/helpers/utils.js +267 -0
  195. package/blz-security/implementations/cache.js +90 -0
  196. package/blz-security/implementations/oidc.js +404 -0
  197. package/blz-security/implementations/pkceCacheStore.js +23 -0
  198. package/blz-security/implementations/saml.js +10 -0
  199. package/blz-security/implementations/uma.js +63 -0
  200. package/blz-security/implementations/webAuthn.js +9 -0
  201. package/blz-security/implementations/wstg.js +72 -0
  202. package/blz-security/index.js +77 -0
  203. package/blz-security/lab/index.js +27 -0
  204. package/blz-security/middleware/HapiServerAzureAd.js +641 -0
  205. package/blz-security/middleware/HapiServerKeycloak.js +840 -0
  206. package/blz-security/middleware/HapiServerSimToken.js +247 -0
  207. package/blz-security/middleware/hapi.js +515 -0
  208. package/blz-security/middleware/hapiServer.js +974 -0
  209. package/blz-security/navigationMemoryRepository.js +15 -0
  210. package/blz-security/navigationMongoDbRepository.js +73 -0
  211. package/blz-security/secureUrlService.js +47 -0
  212. package/blz-security/securityService.js +409 -0
  213. package/blz-security/sqlInjectionGuard.js +162 -0
  214. package/blz-security/templates/forbidden.html +0 -0
  215. package/blz-security/templates/session-iframe-azure-ad.html +7 -0
  216. package/blz-security/templates/session-iframe.html +73 -0
  217. package/blz-security/templates/unauthorized.html +1 -0
  218. package/blz-security/xssGuard.js +87 -0
  219. package/blz-strings/index.js +167 -0
  220. package/blz-uuid/index.js +7 -0
  221. package/blz-yaml/index.js +19 -0
  222. package/index.js +84 -0
  223. package/package.json +97 -0
  224. package/process-managers/index.js +422 -0
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ const BlzBase = require("./base");
3
+ const mysql = require("mysql");
4
+ const poolsByName = new Map();
5
+ const _ = require("underscore");
6
+ const dayjs = require("dayjs");
7
+
8
+ async function getPool(config = {}){
9
+ let key = config.name;
10
+ let pool = poolsByName.get(key);
11
+ if(pool) {
12
+ return pool;
13
+ }
14
+ try {
15
+ config.typeCast = function typeCast(field, next) {
16
+ if (field.type === 'TINY' && field.length === 1) {
17
+ return (next() === 1); // 1 = true, 0 = false
18
+ } else if(field.type === 'DATETIME' || field.type === 'DATE') {
19
+ let value = next();
20
+ if (isUtcOffset(value)) {
21
+ value = dayjs(value).format("YYYY-MM-DDTHH:mm:ss");
22
+ }
23
+ return value;
24
+ } else {
25
+ return next();
26
+ }
27
+ };
28
+ config.waitForConnections = config.waitForConnections || true;
29
+ config.connectionLimit = config.connectionLimit || 100;
30
+ config.queueLimit = config.queueLimit || 100;
31
+ pool = mysql.createPool(config);
32
+ poolsByName.set(key, pool);
33
+ } catch(error) {
34
+ throw BlzBase.error('MySqlCannotCreateConnection', { config }, error);
35
+ }
36
+ return pool;
37
+ };
38
+
39
+ function getConnection(pool) {
40
+ return new Promise(function(resolve, reject) {
41
+ pool.getConnection(function (error, connection) {
42
+ if(error) {
43
+ console.error(error);
44
+ reject(BlzBase.error('MySqlCannotCreateConnection', { connection }, error));
45
+ return;
46
+ }
47
+ connection.name = pool.name;
48
+ resolve(connection);
49
+ });
50
+ });
51
+ }
52
+
53
+ const createConnection = async (config) => await getConnection(await getPool(config));
54
+
55
+ function beginTransaction(connection) {
56
+ return new Promise(function(resolve, reject) {
57
+ connection.beginTransaction(function(err){
58
+ if(err) {
59
+ reject(BlzBase.error('MySqlCannotBeginTransaction', { connection }, err));
60
+ return;
61
+ }
62
+ resolve();
63
+ });
64
+ });
65
+ };
66
+
67
+ function commitTransaction(connection) {
68
+ return new Promise(function(resolve, reject) {
69
+ connection.commit(function(err){
70
+ if(err) {
71
+ reject(BlzBase.error('MySqlCannotCommitTransaction', { connection }, err));
72
+ return;
73
+ }
74
+ resolve();
75
+ });
76
+ });
77
+ };
78
+
79
+ function rollbackTransaction(connection) {
80
+ return new Promise(function(resolve, reject) {
81
+ connection.rollback(function(err){
82
+ if(err) {
83
+ reject(BlzBase.error('MySqlCannotRollBackTransaction', { connection }, err));
84
+ return;
85
+ }
86
+ resolve();
87
+ });
88
+ });
89
+ };
90
+
91
+ async function close(connection) {
92
+ connection.release();
93
+ connection.destroy();
94
+ }
95
+
96
+ async function terminate() {
97
+ let reject = [];
98
+ for (const [, pool] of poolsByName) {
99
+ try {
100
+ await pool.end();
101
+ } catch(error) {
102
+ reject.push(error);
103
+ }
104
+ }
105
+ poolsByName.clear();
106
+ if(_.isEmpty(reject)) {
107
+ return true;
108
+ }
109
+ throw new Error(reject);
110
+ }
111
+
112
+ function isUtcOffset(date) {
113
+ if (_.isNull(date) || _.isUndefined(date) || !_.isString(date)) {
114
+ return false;
115
+ }
116
+ const match = date.match(/^(.*)([+-])(\d{2})?:?(\d{2})$/);
117
+ return (!_.isNull(match)) && ((!_.isUndefined(match[3]) && (match[3] !== '00')) || (!_.isUndefined(match[4]) && (match[4] !== '00')));
118
+ }
119
+
120
+ module.exports = {
121
+ beginTransaction,
122
+ close,
123
+ commitTransaction,
124
+ createConnection,
125
+ getConnection,
126
+ getPool,
127
+ rollbackTransaction,
128
+ terminate
129
+ };
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ const {convertValueToDb } = require("./execute-non-query");
3
+ const BlzBase = require("./base");
4
+
5
+ async function executeBulkInsert(connection, sql, rows, options) {
6
+ const query = sql + ' ?'
7
+ const list = []
8
+ for(let i = 0; i < rows.length; i++) {
9
+ const row = rows[i]
10
+ const values = []
11
+ for(let j = 0; j < row.length; j++) {
12
+ const value = convertValueToDb(row[j])
13
+ values.push(value)
14
+ }
15
+ list.push(values)
16
+ }
17
+ return new Promise(function(resolve, reject){
18
+ connection.query(query, [list], function(error, result, fields) {
19
+ if(error) {
20
+ reject(BlzBase.error('RdsMySqlExecuteError', { name: connection.name, query, rows }, error));
21
+ return;
22
+ }
23
+ if (options.autoincrementalData) {
24
+ const start = result.insertId
25
+ const end = result.insertId + (result.affectedRows - 1)
26
+ const ids= []
27
+ for (let i = start; i <= end; i++)ids.push(i)
28
+ resolve({ ids, affectedRows: result.affectedRows });
29
+ } else {
30
+ resolve({affectedRows: result.affectedRows});
31
+ }
32
+ })
33
+ })
34
+ }
35
+ module.exports = executeBulkInsert;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ const {convertValueToDb } = require("./execute-non-query");
3
+ const BlzBase = require("./base");
4
+ const SqlString = require('sqlstring')
5
+
6
+ async function executeBulkMerge(connection, sql, rows, options) {
7
+ const list = []
8
+ for(let i = 0; i < rows.length; i++) {
9
+ const row = rows[i]
10
+ const values = []
11
+ for(let j = 0; j < row.length; j++) {
12
+ const column = options.columns[j]
13
+ let value = convertValueToDb(row[j])
14
+ if ( ['string','date','datetime','time'].includes(column.type)) {
15
+ value = SqlString.escape(value)
16
+ }
17
+ values.push(value)
18
+ }
19
+ list.push(`(${values.join(',')})`)
20
+ }
21
+ const _sql = []
22
+ _sql.push('INSERT INTO ' + options.rdsTable.tableName + ' (')
23
+ _sql.push(options.setsFields.map(p=> '`'+p+'`').join(', '))
24
+ _sql.push(')\n\rVALUES\n\r')
25
+ _sql.push(list.join(','))
26
+ _sql.push('\n\rON DUPLICATE KEY UPDATE\n\r')
27
+ let first = true
28
+ for( const field of options.setsFields.map(p=> '`'+p+'`')) {
29
+ _sql.push((first? ' ': ',\n\r ') + field + ' = VALUES(' + field + ')')
30
+ first = false
31
+ }
32
+ _sql.push(';')
33
+ const query = _sql.join('')
34
+
35
+ return new Promise(function(resolve, reject){
36
+ connection.query(query, null, function(error, result, fields) {
37
+ if(error) {
38
+ reject(BlzBase.error('RdsMySqlExecuteError', { name: connection.name, query, rows }, error));
39
+ return;
40
+ }
41
+ resolve({affectedRows: result.affectedRows});
42
+ })
43
+ })
44
+ }
45
+ module.exports = executeBulkMerge;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ const _ = require('underscore');
3
+ const BlzBase = require("./base");
4
+ const toUnnamed = require('named-placeholders')();
5
+ /**
6
+ * @param {*} connection
7
+ * @param {string} sql
8
+ * @param {[{name: string, value: *}]} [rdsParameters = []]
9
+ * @returns {Promise<{row: number, id: number}>}
10
+ * @public
11
+ */
12
+ async function executeNonQuery(connection, sql, rdsParameters, options) {
13
+ let query = sql, parameters = [], rs = null;
14
+ try {
15
+ if(!_.isEmpty(rdsParameters)) {
16
+ [query, parameters] = toUnnamed(sql, BlzBase.reduceParameters(rdsParameters, options));
17
+ }
18
+ } catch(error) {
19
+ throw BlzBase.error('RdsAuroraExecuteError', { name: connection.name, sql, parameters }, error);
20
+ }
21
+ return new Promise(function(resolve, reject) {
22
+ connection.query(query, parameters, function(err, result, fields) {
23
+ if(err) {
24
+ reject(BlzBase.error('RdsAuroraExecuteError', { name: connection.name, sql, parameters }, err));
25
+ return;
26
+ }
27
+ resolve({
28
+ rowsAffected : result.affectedRows,
29
+ id : result.insertId
30
+ });
31
+ });
32
+ })
33
+ }
34
+ module.exports = { executeNonQuery }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ const _ = require('underscore');
3
+ const toUnnamed = require('named-placeholders')();
4
+ const BlzBase = require("./base");
5
+
6
+ /**
7
+ * @param {*} connection
8
+ * @param {string} sql
9
+ * @param {[{name: string, value: *}]} [rdsParameters = []]
10
+ * @public
11
+ */
12
+ async function executeQuery(connection, sql, rdsParameters = [], options) {
13
+ let query = sql, parameters = [];
14
+ try {
15
+ if(!_.isEmpty(rdsParameters)) {
16
+ [query, parameters] = toUnnamed(sql, BlzBase.reduceParameters(rdsParameters, options));
17
+ }
18
+ } catch(error) {
19
+ throw BlzBase.error('RdsMySqlExecuteError', { name: connection.name, sql, parameters }, error);
20
+ }
21
+ return new Promise(function(resolve, reject){
22
+ connection.query(query, parameters, function(error, results, fields) {
23
+ if(error) {
24
+ reject(BlzBase.error('RdsMySqlExecuteError', { name: connection.name, sql, parameters }, error));
25
+ return;
26
+ }
27
+ resolve({resultSet: new ResultSet(results, fields)});
28
+ });
29
+ });
30
+ }
31
+
32
+ function ResultSet(results, fields) {
33
+ return {
34
+ getRow: async function() {
35
+ let data = results.shift();
36
+ if(!data) {
37
+ return null;
38
+ }
39
+ return _.map(fields, field =>
40
+ data[field.name]
41
+ );
42
+ },
43
+ close: async function() {
44
+ results = null;
45
+ fields = null;
46
+ return true;
47
+ }
48
+ }
49
+ }
50
+ module.exports = executeQuery;
@@ -0,0 +1,41 @@
1
+ const _ = require("underscore");
2
+ const {executeNonQuery } = require("./execute-non-query");
3
+ const executeQuery = require("./execute-query");
4
+ const executeBulkInsert = require("./execute-bulk-insert");
5
+ const executeBulkMerge = require("./execute-bulk-merge");
6
+ const executeProcedure = require("./stored-procedure");
7
+ const {
8
+ beginTransaction,
9
+ close,
10
+ commitTransaction,
11
+ createConnection: createRdsConnection,
12
+ rollbackTransaction,
13
+ terminate
14
+ } = require("./connection-manager");
15
+
16
+ process.on('exit', async function () {
17
+ await terminate();
18
+ });
19
+
20
+ module.exports = {
21
+ syntaxis: require("./syntaxis.json"),
22
+ executeProcedure,
23
+ executeSql: async function (connection, sql, parameters, options = {}) {
24
+ if(sql.indexOf("call") != -1 ) {
25
+ return await executeProcedure(connection, sql, parameters);
26
+ } else if(_.has(options, "bulkInsert")) {
27
+ return await executeBulkInsert(connection, sql, parameters, options);
28
+ } else if(_.has(options, "bulkMerge")) {
29
+ return await executeBulkMerge(connection, sql, parameters, options);
30
+ } else if(_.has(options, "queryOne") || _.has(options, "query")) {
31
+ return await executeQuery(connection, sql, parameters, options);
32
+ } else {
33
+ return await executeNonQuery(connection, sql, parameters, options);
34
+ }
35
+ },
36
+ beginTransaction,
37
+ close,
38
+ createRdsConnection,
39
+ commitTransaction,
40
+ rollbackTransaction,
41
+ }
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ const mysql = require("mysql");
3
+ const _ = require('underscore');
4
+ const BlzBase = require("./base");
5
+ const toString = Object.prototype.toString;
6
+ //https://dev.mysql.com/doc/dev/connector-nodejs/8.0/tutorial-Getting_Started.html
7
+ //https://dev.mysql.com/doc/x-devapi-userguide/en/using-sql.html
8
+ //https://dev.mysql.com/doc/refman/8.0/en/faqs-stored-procs.html#faq-mysql-can-pass-cursor-in
9
+
10
+ function tryDatetime(value) {
11
+ let convertMilliseconds = function(strMilliseconds) {
12
+ if (strMilliseconds) {
13
+ if (strMilliseconds.length < 3)
14
+ strMilliseconds = strMilliseconds.padEnd(3, '0');
15
+ if (strMilliseconds.length > 3)
16
+ strMilliseconds = strMilliseconds.substr(0, 3);
17
+ return Number(strMilliseconds);
18
+ }
19
+ else
20
+ return 0;
21
+ };
22
+ let strType = toString.call(value);
23
+ if (strType === '[object Date]') {
24
+ return value;
25
+ }
26
+ else if (strType === '[object String]') {
27
+ let match = /^(\d{4})-(\d{1,2})-(\d{1,2})[T,\s](\d{1,2})\:(\d{1,2})\:(\d{1,2})\.?(\d+)?Z?$/.exec(value);
28
+ if (match)
29
+ return new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), Number(match[6] || 0), convertMilliseconds(match[7])));
30
+ }
31
+ return null;
32
+ }
33
+
34
+ function convertValueToDb (value) {
35
+ if (_.isUndefined(value)) {
36
+ return null;
37
+ }
38
+ if(_.isNull(value)) {
39
+ return null;
40
+ }
41
+ if (value === true) {
42
+ return 1;
43
+ }
44
+ if (value === false) {
45
+ return 0;
46
+ }
47
+ let datetime = tryDatetime(value);
48
+ if (datetime) {
49
+ let result = datetime.toJSON();
50
+ if (result.length === 24) {
51
+ result = result.substring(0, 19);
52
+ }
53
+ return result;
54
+ }
55
+ return value;
56
+ }
57
+
58
+ /**
59
+ * @typedef {Object} Parameter
60
+ * @property {boolean} isResultSet
61
+ * @property {string} name
62
+ * @property {*} value
63
+ * @property { 'in' | 'out' | 'in/out' } direction
64
+ * @property {'string' | 'integer' | 'decimal' | 'boolean' | 'datetime' | 'date' | 'time' | 'binary'} type
65
+ */
66
+
67
+ /**
68
+ *
69
+ * @param {mysqlx.Session} session
70
+ * @param {Parameter} parameter
71
+ * @param {*} result
72
+ */
73
+ async function parseOutputParameters(session, parameter, result, time_stamp) {
74
+ let resultSet = null, value = null;
75
+ try {
76
+ resultSet = await (new Promise(function(resolve, reject) {
77
+ let sqlSelect = `SELECT @${parameter.name}_${time_stamp};`;
78
+ session.query(sqlSelect,(err, result, field) => {
79
+ if(err) {
80
+ return reject(err);
81
+ }
82
+ resolve(result);
83
+ })
84
+ }));
85
+ } catch(error) {
86
+ throw BlzBase.error('RdsMysqlCannotConvertParameters', { parameter, result, time_stamp }, error);
87
+ }
88
+ let property = _.property(`@${parameter.name}_${time_stamp}`);
89
+ value = property(_.first(resultSet));
90
+ if(parameter.isResultSet) {
91
+ result[parameter.name] = JSON.parse(value);
92
+ return;
93
+ }
94
+ switch (parameter.type) {
95
+ case 'string':
96
+ result[parameter.name] = BlzBase.convertToString(value);
97
+ break;
98
+ case 'integer':
99
+ result[parameter.name] = BlzBase.convertToInteger(value);
100
+ break;
101
+ case 'decimal':
102
+ result[parameter.name] = BlzBase.convertToDecimal(value);
103
+ break;
104
+ case 'boolean':
105
+ result[parameter.name] = BlzBase.convertToBoolean(value);
106
+ break;
107
+ case 'datetime':
108
+ result[parameter.name] = BlzBase.convertToDatetime(value);
109
+ break;
110
+ case 'date':
111
+ result[parameter.name] = BlzBase.convertToDate(value);
112
+ break;
113
+ case 'time':
114
+ result[parameter.name] = BlzBase.convertToTime(value);
115
+ break;
116
+ case 'binary':
117
+ result[parameter.name] = BlzBase.convertToBinary(value);
118
+ break;
119
+ default:
120
+ throw BlzBase.error('RdsMySqlUnexpectedType', { parameter, result, value });
121
+ }
122
+
123
+ }
124
+
125
+ /**
126
+ * @param {mysqlx.Session} session
127
+ * @param {string} procedure
128
+ * @param {[Parameter]} [parameters=[]]
129
+ * @param {number} time_stamp
130
+ * @returns {string}
131
+ */
132
+ async function parseInputParameters(session, procedure, parameters, time_stamp) {
133
+ for(const parameter of parameters) {
134
+ switch(parameter.direction) {
135
+ case "in":
136
+ case "in/out":
137
+ try {
138
+ await (new Promise(function(resolve, reject) {
139
+ let sqlSet = `SET @${parameter.name}_${time_stamp} = ?;`;
140
+ session.query(sqlSet, [convertValueToDb(parameter.value)], (err, result, field) => {
141
+ if(err) {
142
+ return reject(err);
143
+ }
144
+ resolve();
145
+ })
146
+ }));
147
+ } catch (error) {
148
+ throw BlzBase.error('RdsMySqlInputParameterType', { parameters, time_stamp });
149
+ }
150
+ procedure = procedure
151
+ .replace(`:${parameter.name}`, `@${parameter.name}_${time_stamp}`);
152
+ break;
153
+ case "out":
154
+ try {
155
+ await (new Promise(function(resolve, reject) {
156
+ let sqlSet = `SET @${parameter.name}_${time_stamp} = NULL;`;
157
+ session.query(sqlSet, (err, result, field) => {
158
+ if(err) {
159
+ return reject(err);
160
+ }
161
+ resolve();
162
+ });
163
+ }));
164
+ } catch(error) {
165
+ throw BlzBase.error('RdsMySqlInputParameterType', { parameters, time_stamp });
166
+ }
167
+ procedure = procedure
168
+ .replace(`:${parameter.name}`, `@${parameter.name}_${time_stamp}`);
169
+ break;
170
+ }
171
+ }
172
+ return procedure;
173
+ }
174
+
175
+ /**
176
+ * @param {mysqlx.Session} session
177
+ * @param {string} procedure
178
+ * @param {[Parameter]} [parameters=[]]
179
+ */
180
+ async function executeProcedure(session, procedure, parameters) {
181
+ const time_stamp = Date.now();
182
+ if(_.isArray(parameters)) {
183
+ procedure = await parseInputParameters(session, procedure, parameters, time_stamp);
184
+ }
185
+ try {
186
+ await (new Promise(function(resolve, reject) {
187
+ session.query(procedure, (err, result, field) => {
188
+ if(err) {
189
+ return reject(err);
190
+ }
191
+ resolve(result);
192
+ })
193
+ }));
194
+ } catch (error) {
195
+ throw BlzBase.error('RdsMysqlCannotExecuteProcedure', { session, procedure, parameters }, error);
196
+ }
197
+ let outParameters = {};
198
+ for(const parameter of parameters) {
199
+ if(parameter.direction == "in") {
200
+ continue;
201
+ }
202
+ await parseOutputParameters(session, parameter, outParameters, time_stamp);
203
+ }
204
+ return { outParameters };
205
+ }
206
+
207
+ module.exports = executeProcedure;
@@ -0,0 +1,114 @@
1
+ {
2
+ "selectWithPaging1": "SELECT %1$s LIMIT %4$s",
3
+ "selectWithPagingN": "SELECT %1$s LIMIT %2$s,%4$s",
4
+ "insertAutoIncremental": "INSERT INTO %1$s (%4$s) VALUES (%5$s)",
5
+ "insertConditionalAuto": "INSERT INTO %1$s (%4$s) SELECT %5$s FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM %1$s WHERE %6$s)",
6
+ "insertConditionalAutoIncremental": "INSERT INTO %1$s (%4$s) SELECT %5$s FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM %1$s WHERE %6$s)",
7
+ "selectExists": "SELECT IF(%1$s, 1, 0)",
8
+ "executeStoredProcedure": "call %1$s(%2$s)",
9
+ "procedureResultSet": "implicit",
10
+ "core" : {
11
+ "asc": "%1$s ASC",
12
+ "avg": "ROUND(AVG(%1$s), 8)",
13
+ "count": "COUNT(%1$s)",
14
+ "countDistinct": "COUNT(DISTINCT %1$s)",
15
+ "desc": "%1$s DESC",
16
+ "divide" : "(%1$s / %2$s)",
17
+ "distinct": "DISTINCT %1$s",
18
+ "false" : "0",
19
+ "isNotNull": "(%1$s IS NOT NULL)",
20
+ "isNull": "(%1$s IS NULL)",
21
+ "like": "(%1$s LIKE %2$s)",
22
+ "max": "MAX(%1$s)",
23
+ "min": "MIN(%1$s)",
24
+ "nvl": "IFNULL(%1$s, %2$s)",
25
+ "parameter": ":%1$s",
26
+ "remainder": "MOD(%1$s,%2$s)",
27
+ "sum": "SUM(%1$s)",
28
+ "true" : "1"
29
+ },
30
+ "datetimes" : {
31
+ "addDays": "DATE_ADD(%1$s, INTERVAL %2$s DAY)",
32
+ "addHours": "DATE_ADD(%1$s, INTERVAL %2$s HOUR)",
33
+ "addMilliseconds": "DATE_ADD(%1$s, INTERVAL (%2$s*1000) MICROSECOND)",
34
+ "addMinutes": "DATE_ADD(%1$s, INTERVAL %2$s MINUTE)",
35
+ "addMonths": "DATE_ADD(%1$s, INTERVAL %2$s MONTH)",
36
+ "addSeconds": "DATE_ADD(%1$s, INTERVAL %2$s SECOND)",
37
+ "addYears": "DATE_ADD(%1$s, INTERVAL %2$s YEAR)",
38
+ "date": "STR_TO_DATE('%1$s-%2$s-%3$s 0:0:0', '%Y-%m-%d %H:%i:%S')",
39
+ "dateDiff": "DATEDIFF(%1$s,%2$s)",
40
+ "datetime": "STR_TO_DATE('%1$s-%2$s-%3$s %4$s:%5$s:%6$s', '%Y-%m-%d %H:%i:%S')",
41
+ "datetimeDiff": "TRUNCATE(TIMESTAMPDIFF(MICROSECOND,%2$s,%1$s)/1000,0)",
42
+ "day": "DAY(%1$s)",
43
+ "hour": "HOUR(%1$s)",
44
+ "millisecond": "TRUNCATE(MICROSECOND(%1$s)/1000,0)",
45
+ "minute": "MINUTE((%1$s))",
46
+ "month": "MONTH(%1$s)",
47
+ "monthText": "MONTHNAME(%1$s)",
48
+ "now": "UTC_TIMESTAMP",
49
+ "second": "SECOND(%1$s)",
50
+ "subtractDays": "DATE_SUB(%1$s, INTERVAL %2$s DAY)",
51
+ "subtractHours": "DATE_SUB(%1$s, INTERVAL %2$s HOUR)",
52
+ "subtractMilliseconds": "DATE_SUB(%1$s, INTERVAL (%2$s*1000) MICROSECOND)",
53
+ "subtractMinutes": "DATE_SUB(%1$s, INTERVAL %2$s MINUTE)",
54
+ "subtractSeconds": "DATE_SUB(%1$s, INTERVAL %2$s SECOND)",
55
+ "today": "CURDATE()",
56
+ "time": "TIME(STR_TO_DATE('2018-1-1 %1$s:%2$s:%3$s', '%Y-%m-%d %H:%i:%S'))",
57
+ "timeDiff": "TIME_TO_SEC(TIMEDIFF(%1$s,%2$s)) * 1000",
58
+ "week": "WEEK(%1$s) + 1",
59
+ "weekDay": "WEEKDAY(%1$s) + 1",
60
+ "weekDayText": "DATE_FORMAT(%1$s,'%W')",
61
+ "year": "YEAR(%1$s)"
62
+ },
63
+ "math" : {
64
+ "abs": "ABS(%1$s)",
65
+ "acos": "ACOS(%1$s)",
66
+ "asin": "ASIN(%1$s)",
67
+ "atan": "ATAN(%1$s)",
68
+ "atan2": "ATAN2(%2$s,%1$s)",
69
+ "ceil": "CEIL(%1$s)",
70
+ "cos": "COS(%1$s)",
71
+ "cosh": "((EXP(%1$s) + EXP(%1$s*-1))/2)",
72
+ "exp": "EXP(%1$s)",
73
+ "floor": "FLOOR(%1$s)",
74
+ "logBase": "LOG(%2$s,%1$s)",
75
+ "log": "LOG(EXP(1),%1$s)",
76
+ "log10": "LOG10(%1$s)",
77
+ "pow": "POW(%1$s,%2$s)",
78
+ "random": "RAND()",
79
+ "remainder": "MOD(%1$s,%2$s)",
80
+ "round": "ROUND(%1$s,0)",
81
+ "roundWithDecimals": "ROUND(%1$s,%2$s)",
82
+ "sign": "SIGN(%1$s)",
83
+ "sin": "SIN(%1$s)",
84
+ "sinh": "((EXP(%1$s) - EXP(%1$s*-1))/2)",
85
+ "sqrt": "SQRT(%1$s)",
86
+ "tan": "TAN(%1$s)",
87
+ "tanh": "(EXP(%1$s) - EXP(%1$s*-1))/(EXP(%1$s) + EXP(%1$s*-1))",
88
+ "trunc": "TRUNCATE(%1$s,0)",
89
+ "truncWithDecimals": "TRUNCATE(%1$s,%2$s)"
90
+ },
91
+ "strings": {
92
+ "concat": "CONCAT_WS('',{[,]})",
93
+ "contains": "(INSTR(%1$s,%2$s)>0)",
94
+ "endsWith": "(%1$s LIKE CONCAT('%%',%2$s))",
95
+ "indexOf": "INSTR(IFNULL(%1$s,''),%2$s)-1",
96
+ "isNullOrEmpty": "(BINARY COALESCE(%1$s, '')='')",
97
+ "isNullOrWhiteSpace": "(COALESCE(%1$s, '')='')",
98
+ "join": "CONCAT_WS(%1$s,{[,]})",
99
+ "lastIndexOf": "IF(INSTR(COALESCE(REVERSE(%1$s),''),REVERSE(%2$s))=0,-1,INSTR(REVERSE(%1$s),REVERSE(%2$s))-1+LENGTH(%1$s)-LENGTH(%2$s))",
100
+ "length": "IFNULL(LENGTH(%1$s),0)",
101
+ "padLeft": "LPAD(%1$s,%2$s,' ')",
102
+ "padLeftPattern": "LPAD(%1$s,%2$s,%3$s)",
103
+ "padRight": "RPAD(%1$s,%2$s,' ')",
104
+ "padRightPattern": "RPAD(%1$s,%2$s,%3$s)",
105
+ "replace": "REPLACE(%1$s,%2$s,%3$s)",
106
+ "startsWith": "(%1$s LIKE CONCAT(%2$s,'%%'))",
107
+ "substring": "SUBSTR(%1$s,%2$s+1,%3$s)",
108
+ "toLower": "LOWER(%1$s)",
109
+ "toUpper": "UPPER(%1$s)",
110
+ "trim": "TRIM(%1$s)",
111
+ "trimEnd": "RTRIM(%1$s)",
112
+ "trimStart": "LTRIM(%1$s)"
113
+ }
114
+ }