@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,540 @@
1
+ const oracledb = require("oracledb");
2
+ const _ = require("underscore");
3
+ const { h3lp } = require('h3lp');
4
+ // check blzBase location
5
+ const Path = require('path');
6
+ const Fs = require('fs-extra');
7
+ const blzBaseSuite = Path.resolve(__dirname, '../../blz-core/sources-dual/index.js');
8
+ let BlzBase = null;
9
+ if (Fs.existsSync(blzBaseSuite)) {
10
+ BlzBase = require('../../blz-core/sources-dual/index.js');
11
+ } else {
12
+ BlzBase = require('../blz-core/dual/index.js');
13
+ }
14
+ oracledb.fetchAsBuffer = [oracledb.BLOB];
15
+ oracledb.fetchAsString = [oracledb.CLOB, oracledb.DATE, oracledb.NUMBER];
16
+
17
+ let poolsByName = Object.create(null);
18
+
19
+ const getPool = async function (connection) {
20
+ try {
21
+ if (!connection.name) {
22
+ throw new Error('You must provide a connnection name');
23
+ }
24
+ let key = connection.name;
25
+ let pool = poolsByName[key];
26
+ if (pool) {
27
+ return pool;
28
+ }
29
+
30
+ connection.connectString = connection.dataSource;
31
+ connection = _.omit(connection, "dataSource", "providerName");
32
+ connection.sessionCallback = makeInitSessionCallback({ schema: connection.schema })
33
+ // Enable instant client mode in Node.js
34
+ if (process.env.LD_LIBRARY_PATH){
35
+ oracledb.initOracleClient( { libDir: process.env.LD_LIBRARY_PATH, configDir: '', thin: false} );
36
+ }
37
+ pool = await oracledb.createPool(connection);
38
+ pool.connectionName = connection.name;
39
+ poolsByName[key] = pool;
40
+ return pool;
41
+ }
42
+ catch (err) {
43
+ throw new Error('Oracle cannot create pool for ' + connection.name + ': ' + err.message);
44
+ }
45
+ };
46
+
47
+ const makeInitSessionCallback = ({ schema } = {}) => (oraConnection, requestedTag, callbackFn) => {
48
+ const sessionSets = [
49
+ ['NLS_DATE_FORMAT', `'YYYY-MM-DD"T"hh24:mi:ss'`],
50
+ schema ? ['CURRENT_SCHEMA', `${schema}`] : undefined
51
+ ]
52
+
53
+ const sessionSetsString = sessionSets
54
+ .filter(Boolean)
55
+ .map(([key, value]) => `${key}=${value}`)
56
+ .join(' ')
57
+
58
+ oraConnection.execute(`ALTER SESSION SET ${sessionSetsString}`, callbackFn)
59
+ }
60
+
61
+ const tryDatetime = function (value) {
62
+ let strType = toString.call(value);
63
+ if (strType === '[object Date]') {
64
+ return value;
65
+ }
66
+ else if (strType === '[object String]') {
67
+ 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);
68
+ if (match) {
69
+ const probableDate = new Date(value);
70
+ if (probableDate.toString() !== 'Invalid Date') {
71
+ return probableDate;
72
+ }
73
+ }
74
+ }
75
+ return null;
76
+ };
77
+ const convertMilliseconds = function(strMilliseconds) {
78
+ if (strMilliseconds) {
79
+ if (strMilliseconds.length < 3)
80
+ strMilliseconds = strMilliseconds.padEnd(3, '0');
81
+ if (strMilliseconds.length > 3)
82
+ strMilliseconds = strMilliseconds.substr(0, 3);
83
+ return Number(strMilliseconds);
84
+ }
85
+ else
86
+ return 0;
87
+ };
88
+
89
+ const convertResultSetToArray = function (resultSet, results) {
90
+ return resultSet.getRow()
91
+ .then((row) => {
92
+ if (row) {
93
+ results.push(row);
94
+ return convertResultSetToArray(resultSet, results);
95
+ }
96
+ else
97
+ return resultSet.close()
98
+ .then(() => {
99
+ return results;
100
+ });
101
+ })
102
+ .catch((err) => {
103
+ resultSet.close();
104
+ throw BlzBase.error('ErrorFetchingRowsForConnection', {}, err);
105
+ });
106
+ }
107
+
108
+ const getParameterType = function (type) {
109
+ switch (type) {
110
+ case 'string':
111
+ return oracledb.STRING
112
+ case 'integer':
113
+ case 'decimal':
114
+ case 'boolean':
115
+ return oracledb.NUMBER
116
+ case 'datetime':
117
+ case 'date':
118
+ case 'time':
119
+ return oracledb.DATE
120
+ case 'binary':
121
+ return oracledb.BUFFER
122
+ case 'CLOB':
123
+ return oracledb.CLOB;
124
+ case 'BLOB':
125
+ return oracledb.CLOB;
126
+ case 'VARCHAR':
127
+ case 'VARCHAR2':
128
+ return oracledb.STRING;
129
+ default:
130
+ return oracledb.STRING
131
+ }
132
+ }
133
+
134
+ const getOraParameters = function (parameters,options) {
135
+ let oraParameters = {};
136
+ if (parameters)
137
+ for (let i = 0; i < parameters.length; i++) {
138
+ let parameter = parameters[i];
139
+ let oraParameter = {};
140
+ // checks if i need to convert nodejs to oracle representation (bool -> 0,1) etcs
141
+ if (parameter.direction === 'in' || parameter.direction === 'in/out') {
142
+ if (parameter.value === undefined || parameter.value === null)
143
+ oraParameter.val = null;
144
+ else if (parameter.value === true)
145
+ oraParameter.val = 1;
146
+ else if (parameter.value === false)
147
+ oraParameter.val = 0;
148
+ else {
149
+ if (parameter.columnInfo && parameter.columnInfo.type === 'string') {
150
+ oraParameter.val = parameter.value
151
+ } else {
152
+ let datetime = tryDatetime(parameter.value);
153
+ if (datetime) {
154
+ oraParameter.val = datetime;
155
+ // Old Date management
156
+ // let tmp = datetime.toJSON();
157
+ // if (tmp.length === 24)
158
+ // tmp = tmp.substring(0, 19);
159
+ // oraParameter.val = tmp;
160
+ }
161
+ else {
162
+ oraParameter.val = parameter.value;
163
+ }
164
+ }
165
+ }
166
+ }
167
+ // binds de in out
168
+ if (parameter.direction === 'in')
169
+ oraParameter.dir = oracledb.BIND_IN;
170
+ else if (parameter.direction === 'in/out')
171
+ oraParameter.dir = oracledb.BIND_INOUT;
172
+ else if (parameter.direction === 'out')
173
+ oraParameter.dir = oracledb.BIND_OUT;
174
+ // selects the parameter type
175
+ if (parameter.isResultSet)
176
+ oraParameter.type = oracledb.CURSOR;
177
+ else {
178
+ if (parameter.dbTypes){
179
+ const oracleEntry = parameter.dbTypes.find(entry => entry.providerName === 'Oracle');
180
+ parameter.dbType = getParameterType(oracleEntry.dbType);
181
+ } else if (parameter.type) {
182
+ parameter.dbType = getParameterType(parameter.type);
183
+ }
184
+ else {
185
+ parameter.dbType = inferDbTypeFromValue(parameter.value);
186
+ }
187
+ oraParameter.type = parameter.dbType;
188
+ }
189
+ oraParameters[parameter.name] = oraParameter;
190
+ }
191
+ if (options && options.autoincrementalData)
192
+ oraParameters['ScalarOutput'] = { val: null, dir: oracledb.BIND_OUT, type: oracledb.NUMBER };
193
+ return oraParameters
194
+ }
195
+
196
+ const getOraOptions = function (options , bindDefs) {
197
+ let oraOptions = { autoCommit: !options.isTransactionRequest };
198
+ if (options && (options.query || options.queryOne)) {
199
+ oraOptions.resultSet = true;
200
+ }
201
+ if (bindDefs) {
202
+ oraOptions.bindDefs = bindDefs
203
+ }
204
+ return oraOptions;
205
+ }
206
+
207
+ const convertValueFromType = async function (value, type) {
208
+ switch (type) {
209
+ case 'string': {
210
+ return BlzBase.convertToString(value);
211
+ }
212
+ case 'integer': {
213
+ return BlzBase.convertToInteger(value);
214
+ }
215
+ case 'decimal': {
216
+ return BlzBase.convertToDecimal(value);
217
+ }
218
+ case 'boolean': {
219
+ return BlzBase.convertToBoolean(value);
220
+ }
221
+ case 'datetime': {
222
+ return BlzBase.convertToDatetime(value);
223
+ }
224
+ case 'date': {
225
+ return BlzBase.convertToDate(value);
226
+ }
227
+ case 'time': {
228
+ return BlzBase.convertToTime(value);
229
+ }
230
+ case 'binary': {
231
+ return BlzBase.convertToBinary(value);
232
+ }
233
+ default:{
234
+ // If i have a clob, or special type, the case might not be straightforward
235
+ if (value._type.name === 'DB_TYPE_CLOB' ) {
236
+ return await oraResult.outBinds[parameter.name].getData();
237
+ break;
238
+ }
239
+ }
240
+ }
241
+ }
242
+
243
+ const getResult = async function (parameters, oraResult, options) {
244
+ let result = {};
245
+ result.rowsAffected = oraResult.rowsAffected;
246
+ result.outParameters = {};
247
+ if (parameters)
248
+ for (let i = 0; i < parameters.length; i++) {
249
+ let parameter = parameters[i];
250
+ if (parameter.direction === 'out' || parameter.direction === 'in/out') {
251
+ let value = oraResult.outBinds[parameter.name];
252
+ if (parameter.isResultSet)
253
+ value = await convertResultSetToArray(value, []);
254
+ else {
255
+ if (value && typeof value.type === 'string') {
256
+ value = await convertValueFromType(value, value.type);
257
+ } else if (value && value._type && typeof value._type.name === 'string' && value._type.name === 'DB_TYPE_CLOB') {
258
+ value = await oraResult.outBinds[parameter.name].getData();
259
+ } else if (parameter && typeof parameter.type === 'string') {
260
+ value = await convertValueFromType(value, parameter.type);
261
+ } else {
262
+ console.warn('Could not resolve out parameter type');
263
+ }
264
+ }
265
+ result.outParameters[parameter.name] = value;
266
+ }
267
+ }
268
+ if (options && options.autoincrementalData) {
269
+ result.id = null;
270
+ if (oraResult.outBinds && oraResult.outBinds.ScalarOutput) {
271
+ result.id = oraResult.outBinds.ScalarOutput;
272
+ if (Array.isArray(result.id))
273
+ result.id = result.id[0];
274
+ }
275
+ }
276
+ if (options && (options.query || options.queryOne))
277
+ result.resultSet = oraResult.resultSet;
278
+ return result;
279
+ }
280
+
281
+ process.on('exit', async function () {
282
+ let promises = [];
283
+ for (let poolName in poolsByName) {
284
+ let pool = poolsByName[poolName];
285
+ promises.push(pool.close());
286
+ }
287
+ poolsByName = null;
288
+ await Promise.all(promises);
289
+ });
290
+
291
+ const getValue = function (source, type) {
292
+ const _type = type ? type.toLowerCase() : typeof source
293
+ switch (_type.toLowerCase()) {
294
+ case 'boolean':
295
+ return source ? 1 : 0
296
+ case 'string':
297
+ return typeof source === 'string' || source === null || source === undefined ? source : source.toString()
298
+ case 'datetime':
299
+ case 'date':
300
+ case 'time':
301
+ return source ? new Date(source) : null
302
+ default:
303
+ return source
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Infers the Oracle DB type from a JavaScript value.
309
+ * @param {*} value - The value to infer the DB type for.
310
+ * @returns {number} oracledb type constant.
311
+ */
312
+ const inferDbTypeFromValue = function (value) {
313
+ if (value === null || value === undefined) {
314
+ return oracledb.STRING; // default to STRING for nulls
315
+ }
316
+
317
+ if (Buffer.isBuffer(value)) {
318
+ return getParameterType('binary');
319
+ }
320
+
321
+ const jsType = typeof value;
322
+
323
+ switch (jsType) {
324
+ case 'string':
325
+ return getParameterType('string');
326
+ case 'number':
327
+ // Decide between integer and decimal if needed
328
+ return Number.isInteger(value) ? getParameterType('integer') : getParameterType('decimal');
329
+ case 'boolean':
330
+ return getParameterType('boolean');
331
+ case 'object':
332
+ if (value instanceof Date) {
333
+ return getParameterType('datetime');
334
+ }
335
+ return getParameterType('string'); // fallback for objects
336
+ default:
337
+ return getParameterType('string');
338
+ }
339
+ }
340
+
341
+
342
+ const rowsToArray = function (columns, rows) {
343
+ const array = []
344
+ const columnsCount = columns.length
345
+ for (const row of rows) {
346
+ const item = {}
347
+ for(let i=0 ; i < columnsCount ; i++) {
348
+ const column = columns[i]
349
+ const value = row[i]
350
+ item[column.name] = getValue(value,column.type)
351
+ }
352
+ array.push(item)
353
+ }
354
+ return array
355
+ }
356
+
357
+ module.exports = {
358
+ syntaxis: require('./syntaxis.json'),
359
+ createRdsConnection: async function (connection) {
360
+ try {
361
+ let oraPool = await getPool(connection);
362
+ let oraConnection = await oraPool.getConnection();
363
+ return oraConnection;
364
+ }
365
+ catch (err) {
366
+ throw err;
367
+ }
368
+ },
369
+ executeSql: async function (connection, sql, parameters, options) {
370
+ if(_.has(options, "bulkInsert")) {
371
+ return await this._executeBulkInsert(connection, sql, parameters, options);
372
+ } else if(_.has(options, "bulkMerge")) {
373
+ return await this._executeBulkMerge(connection, sql, parameters, options);
374
+ } else {
375
+ return await this._executeSql(connection, sql, parameters, options);
376
+ }
377
+ },
378
+ _executeSql: async function (connection, sql, parameters, options) {
379
+ try{
380
+ let oraParameters = getOraParameters(parameters,options);
381
+ let oraOptions = getOraOptions(options)
382
+ let oraResult = await connection.execute(sql, oraParameters, oraOptions);
383
+ const result = await getResult(parameters, oraResult, options);
384
+ return result;
385
+ } catch (err) {
386
+ throw err
387
+ }
388
+ },
389
+ _executeBulkInsert: async function (connection, sql, rows, options) {
390
+ let autoincremental = null
391
+ if (options.autoincrementalData && options.autoincrementalData.pkColumnName) {
392
+ autoincremental = { name: options.autoincrementalData.pkColumnName ,
393
+ alias: options.autoincrementalData.pkColumnAlias,
394
+ sequence: options.autoincrementalData.sequenceName,
395
+ type: options.autoincrementalData.pkColumnType
396
+ }
397
+ }
398
+ const _sql = autoincremental ?
399
+ 'INSERT INTO ' + options.rdsTable.tableName +
400
+ ' (' + autoincremental.name + ',' + options.setsFields.join(', ') +
401
+ ') VALUES ( ' + autoincremental.sequence + '.NEXTVAL, ' + options.setsFields.map((field) => ':' + field).join(', ') + ' ) ' +
402
+ ' RETURNING ' + autoincremental.name + ' INTO :' + autoincremental.name
403
+ : sql + '(' +options.setsFields.map((field) => ':' + field).join(', ') + ' ) '
404
+
405
+ // solve max size for string fields
406
+ const columnsCount = options.columns.length
407
+ for(let i=0 ; i < columnsCount ; i++) {
408
+ const column = options.columns[i]
409
+ if (column.type === 'string') {
410
+ column.size = rows.reduce((max, row) => { return !row[i]?0:row[i].length > max ? row[i].length : max }, 0)
411
+ }
412
+ }
413
+ const bindDefs = {}
414
+ for (const column of options.columns) {
415
+ const bindDef = { type:getDbType(column.type) }
416
+ if (column.type === 'string') {
417
+ bindDef.maxSize = column.size
418
+ }
419
+ bindDefs[column.name] = bindDef
420
+ }
421
+ if (autoincremental) {
422
+ bindDefs[autoincremental.name] = { type: getDbType(autoincremental.type), dir: oracledb.BIND_OUT}
423
+ }
424
+ const oraOptions = getOraOptions(options,bindDefs)
425
+ const data = rowsToArray(options.columns,rows)
426
+ try {
427
+ const result = await connection.executeMany(_sql, data, oraOptions)
428
+ if (autoincremental) {
429
+ const ids = []
430
+ for (const i in result.outBinds) {
431
+ ids.push(result.outBinds[i][autoincremental.name][0])
432
+ }
433
+ return { rowsAffected: result.rowsAffected, ids }
434
+ } else {
435
+ return { rowsAffected: result.rowsAffected }
436
+ }
437
+ } catch (err) {
438
+ console.log(err)
439
+ throw err
440
+ }
441
+ },
442
+ _executeBulkMerge: async function (connection, sql, rows, options) {
443
+ // example: https://stackoverflow.com/questions/67881781/how-to-execute-multiple-merge-into-query-on-oracle-db-from-node-js
444
+ let autoincremental = null
445
+ if (options.autoincrementalData && options.autoincrementalData.pkColumnName) {
446
+ autoincremental = { name: options.autoincrementalData.pkColumnName ,
447
+ alias: options.autoincrementalData.pkColumnAlias,
448
+ sequence: options.autoincrementalData.sequenceName,
449
+ type: options.autoincrementalData.pkColumnType
450
+ }
451
+ }
452
+ const _sql = []
453
+ _sql.push('MERGE INTO ' + options.rdsTable.tableName + ' t USING (')
454
+ _sql.push('SELECT ')
455
+ let first = true
456
+ for (const column of options.columns) {
457
+ _sql.push((first?'': ', ') + ':' + column.name + ' AS ' + column.name)
458
+ first = false
459
+ }
460
+ _sql.push('FROM DUAL')
461
+ _sql.push(') s ON (')
462
+ first = true
463
+ for(const field of options.mergeFields) {
464
+ _sql.push((first?'': ' AND ') + 't.' + field + ' = s.' + field )
465
+ first = false
466
+ }
467
+ _sql.push(')')
468
+ _sql.push('WHEN MATCHED THEN UPDATE SET ')
469
+ first = true
470
+ for(const column of options.columns) {
471
+ if(options.mergeFields.includes(column.name)) continue
472
+ _sql.push((first?'': ',') + 't.' + column.name + ' = s.' + column.name)
473
+ first = false
474
+ }
475
+ _sql.push('WHEN NOT MATCHED THEN INSERT (')
476
+ if(autoincremental) {
477
+ _sql.push(autoincremental.name)
478
+ for(const column of options.columns) {
479
+ _sql.push(',' + column.name)
480
+ }
481
+ _sql.push(') VALUES (')
482
+ _sql.push(autoincremental.sequence + '.NEXTVAL')
483
+ for(const column of options.columns) {
484
+ _sql.push(',s.' + column.name)
485
+ }
486
+ } else {
487
+ first = true
488
+ for(const column of options.columns) {
489
+ _sql.push((first?'': ',') + column.name)
490
+ first = false
491
+ }
492
+ _sql.push(') VALUES (')
493
+ first = true
494
+ for(const column of options.columns) {
495
+ _sql.push((first?'': ',') + 's.' + column.name)
496
+ first = false
497
+ }
498
+ }
499
+ _sql.push(')')
500
+ const mergeSql = _sql.join(' ')
501
+
502
+ // solve max size for string fields
503
+ const columnsCount = options.columns.length
504
+ for(let i=0 ; i < columnsCount ; i++) {
505
+ const column = options.columns[i]
506
+ if (column.type === 'string') {
507
+ column.size = rows.reduce((max, row) => { return !row[i]?0:row[i].length > max ? row[i].length : max }, 0)
508
+ }
509
+ }
510
+ const bindDefs = {}
511
+ for (const column of options.columns) {
512
+ const bindDef = { type:getDbType(column.type) }
513
+ if (column.type === 'string') {
514
+ bindDef.maxSize = column.size
515
+ }
516
+ bindDefs[column.name] = bindDef
517
+ }
518
+ const oraOptions = getOraOptions(options,bindDefs)
519
+ const data = rowsToArray(options.columns,rows)
520
+ try {
521
+ const result = await connection.executeMany(mergeSql, data, oraOptions)
522
+ return { rowsAffected: result.rowsAffected }
523
+ } catch (err) {
524
+ console.log(err)
525
+ throw err
526
+ }
527
+ },
528
+ close(nativeConnection) {
529
+ return nativeConnection.close();
530
+ },
531
+ beginTransaction(nativeConnection) {
532
+ //se utiliza la variable isTransactionRequest
533
+ },
534
+ commitTransaction(nativeConnection) {
535
+ return nativeConnection.commit();
536
+ },
537
+ rollbackTransaction(nativeConnection) {
538
+ return nativeConnection.rollback();
539
+ }
540
+ };
@@ -0,0 +1,112 @@
1
+ {
2
+ "selectWithPaging1": "select /*+ FIRST_ROWS */ templimit.* from (SELECT %1$s) templimit where rownum <= %3$s",
3
+ "selectWithPagingN": "select res.* from (select /*+ FIRST_ROWS */ templimit.*, rownum r from (SELECT %1$s) templimit where rownum <= %3$s) res where r > %2$s",
4
+ "insertAutoIncremental": "INSERT INTO %1$s (%3$s, %4$s) VALUES (%2$s.NEXTVAL, %5$s) RETURNING %3$s INTO :ScalarOutput",
5
+ "insertConditional":"BEGIN \r\n INSERT INTO %1$s (%4$s) SELECT %5$s FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM %1$s WHERE %6$s);\r\nSELECT %3$s INTO :ScalarOutput FROM %1$s WHERE %6$s AND ROWNUM = 1;\r\nEND;",
6
+ "insertConditionalAutoIncremental":"DECLARE\r\n v_ID %1$s.%3$s%TYPE;\r\nBEGIN\r\nSELECT %2$s.NEXTVAL INTO v_ID FROM DUAL;\r\nINSERT INTO %1$s (%3$s, %4$s) SELECT v_ID, %5$s FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM %1$s WHERE %6$s);\r\nIF SQL%ROWCOUNT = 1 THEN\r\nSELECT v_ID INTO :ScalarOutput FROM dual;\r\nEND IF;\r\nEND;",
7
+ "selectExists": "SELECT CASE WHEN %1$s THEN 1 ELSE 0 END FROM DUAL",
8
+ "executeStoredProcedure": "BEGIN %1$s(%2$s); END;",
9
+ "storedProcedureResultSet": "explicit",
10
+ "core": {
11
+ "asc": "%1$s ASC NULLS FIRST",
12
+ "avg": "ROUND(AVG(%1$s), 8)",
13
+ "count": "COUNT(%1$s)",
14
+ "countDistinct": "COUNT(DISTINCT %1$s)",
15
+ "desc": "%1$s DESC NULLS LAST",
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": "NVL(%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": "(%1$s+%2$s)",
32
+ "addHours": "(%1$s+(%2$s/24))",
33
+ "addMilliseconds": "(%1$s+(%2$s/(24*60*60*1000)))",
34
+ "addMinutes": "(%1$s+(%2$s/(24*60)))",
35
+ "addMonths": "ADD_MONTHS(%1$s, %2$s)",
36
+ "addSeconds": "(%1$s+(%2$s/(24*60*60)))",
37
+ "addYears": "ADD_MONTHS(%1$s, %2$s*12)",
38
+ "date": "TO_DATE('%1$s-%2$s-%3$s 00:00:00','YYYY-MM-DD HH24:MI:SS')",
39
+ "dateDiff": "(%1$s-%2$s)",
40
+ "datetime": "TO_DATE('%1$s-%2$s-%3$s %4$s:%5$s:%6$s','YYYY-MM-DD HH24:MI:SS')",
41
+ "datetimeDiff": "((%1$s-%2$s)*24*60*60*1000)",
42
+ "day": "TO_NUMBER(TO_CHAR(%1$s,'DD'))",
43
+ "hour": "TO_NUMBER(TO_CHAR(%1$s,'HH24'))",
44
+ "millisecond": "(CASE WHEN %1$s IS NULL THEN NULL ELSE 0 END)",
45
+ "minute": "TO_NUMBER(TO_CHAR(%1$s,'MI'))",
46
+ "month": "TO_NUMBER(TO_CHAR(%1$s,'MM'))",
47
+ "monthText": "TRIM(TO_CHAR(%1$s,'Month'))",
48
+ "now": "CAST(SYSTIMESTAMP AT TIME ZONE 'UTC' AS DATE)",
49
+ "second": "TO_NUMBER(TO_CHAR(%1$s,'SS'))",
50
+ "subtractDays": "(%1$s-%2$s)",
51
+ "subtractMilliseconds": "(%1$s-(%2$s/(24*60*60*1000)))",
52
+ "subtractMinutes": "(%1$s-(%2$s/(24*60)))",
53
+ "subtractSeconds": "(%1$s-(%2$s/(24*60*60)))",
54
+ "time": "TO_DATE('1970-01-01 %1$s:%2$s:%3$s','YYYY-MM-DD HH24:MI:SS')",
55
+ "timeDiff": "((%1$s-%2$s)*24*60*60*1000)",
56
+ "today": "TRUNC(CAST(SYSTIMESTAMP AT TIME ZONE 'UTC' AS DATE))",
57
+ "week": "TO_NUMBER(TO_CHAR(%1$s,'WW'))",
58
+ "weekDay": "(TO_NUMBER(TO_CHAR(%1$s,'D'))-1)",
59
+ "weekDayText": "TO_CHAR(%1$s,'FmDay','nls_date_language=english')",
60
+ "year": "TO_NUMBER(TO_CHAR(%1$s,'YYYY'))"
61
+ },
62
+ "math":{
63
+ "abs": "ABS(%1$s)",
64
+ "acos": "ACOS(%1$s)",
65
+ "asin": "ASIN(%1$s)",
66
+ "atan": "ATAN(%1$s)",
67
+ "atan2": "ATAN2(%2$s,%1$s)",
68
+ "ceil": "CEIL(%1$s)",
69
+ "cos": "COS(%1$s)",
70
+ "cosh": "COSH(%1$s)",
71
+ "exp": "EXP(%1$s)",
72
+ "floor": "FLOOR(%1$s)",
73
+ "logBase": "LOG(%2$s,%1$s)",
74
+ "log": "LOG(EXP(1),%1$s)",
75
+ "log10": "LOG(10,%1$s)",
76
+ "pow": "POWER(%1$s,%2$s)",
77
+ "random": "DBMS_RANDOM.VALUE",
78
+ "round": "ROUND(%1$s)",
79
+ "roundWithDecimals": "ROUND(%1$s,%2$s)",
80
+ "sign": "SIGN(%1$s)",
81
+ "sin": "SIN(%1$s)",
82
+ "sinh": "SINH(%1$s)",
83
+ "sqrt": "SQRT(%1$s)",
84
+ "tan": "TAN(%1$s)",
85
+ "tanh": "TANH(%1$s)",
86
+ "trunc": "TRUNC(%1$s)",
87
+ "truncWithDecimals": "TRUNC(%1$s,%2$s)"
88
+ },
89
+ "strings": {
90
+ "concat": "({[ || ]})",
91
+ "contains": "(INSTR(%1$s,%2$s)>0)",
92
+ "endsWith": "REGEXP_LIKE(%1$s,'(*)'||%2$s||'$')",
93
+ "indexOf": "(NVL(INSTR(%1$s,%2$s),0)-1)",
94
+ "isNullOrEmpty": "(NVL(LENGTH(%1$s),0)=0) OR (%1$s IS NULL)",
95
+ "isNullOrWhiteSpace": "(NVL(LENGTH(TRIM(%1$s)),0)=0) OR (%1$s IS NULL)",
96
+ "join": "({[ || %1$s || ]})",
97
+ "lastIndexOf": "(NVL(INSTR(%1$s,%2$s,-1),0)-1)",
98
+ "length": "NVL(LENGTH(%1$s),0)",
99
+ "padLeft": "LPAD(%1$s,%2$s)",
100
+ "padLeftPattern": "LPAD(%1$s,%2$s,%3$s)",
101
+ "padRight": "RPAD(%1$s,%2$s)",
102
+ "padRightPattern": "RPAD(%1$s,%2$s,%3$s)",
103
+ "replace": "REPLACE(%1$s,%2$s,%3$s)",
104
+ "startsWith": "REGEXP_LIKE(%1$s,'^'||%2$s||'(*)')",
105
+ "substring": "SUBSTR(%1$s,%2$s+1,%3$s)",
106
+ "toLower": "LOWER(%1$s)",
107
+ "toUpper": "UPPER(%1$s)",
108
+ "trim": "TRIM(%1$s)",
109
+ "trimEnd": "RTRIM(%1$s)",
110
+ "trimStart": "LTRIM(%1$s)"
111
+ }
112
+ }