-
Notifications
You must be signed in to change notification settings - Fork 31
/
oracleDriver.js
255 lines (207 loc) · 6.67 KB
/
oracleDriver.js
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
var optionalRequire = require('./optionalRequire');
var promisify = require('./promisify');
var debug = require('debug')('sworm:oracle');
var swormDebug = require('debug')('sworm');
var _ = require('underscore');
var urlUtils = require('url');
var redactConfig = require('./redactConfig');
var outstandingQueries = require('./outstandingQueries');
var randomstring = require('randomstring');
var cooperative = require('cooperative')
module.exports = function () {
var oracledb = optionalRequire('oracledb');
return {
outstandingQueries: outstandingQueries(),
query: function (query, params, options) {
var resultsPromise = this.execute(replaceParameters(query), params, _.extend({outFormat: oracledb.ARRAY}, options))
if (options.statement || options.insert) {
return resultsPromise.then(function (results) {
var r = {}
if (options.statement) {
r.changes = results.rowsAffected
}
if (options.insert) {
r.id = results.outBinds.returning_into_id[0]
}
return r
})
} else {
return resultsPromise;
}
},
execute: function (query, params, options) {
var self = this;
debug(query, params);
var promise = options.statement || options.insert
? promisify(function (cb) {
self.connection.execute(query, params || {}, options, cb)
})
: this.queryResultSet(query, params || {}, options)
return this.outstandingQueries.execute(promise);
},
queryResultSet: function(query, params, options) {
return this.connection.execute(query, params, _.extend(options, {resultSet: true})).then(function (results) {
var resultSet = results.resultSet
var numberOfRows = oracledb.maxRows || 100
function fetchRows(allRows) {
return resultSet.getRows(numberOfRows).then(function (rows) {
allRows.push(rows)
if (rows.length < numberOfRows) {
return resultSet.close().then(function () {
return allRows
})
} else {
return fetchRows(allRows)
}
})
}
return fetchRows([]).then(function (_rows) {
var rows = _.flatten(_rows, true)
if (options.formatRows === false) {
return rows
} else {
return formatRows(results.metaData, rows)
}
}, function (error) {
return resultSet.close().then(function () {
throw error
})
})
}, function (error) {
if (/NJS-019/.test(error.message)) {
throw new Error('oracle: you cannot pass an SQL statement to db.query(), please use db.statement()')
} else {
throw error
}
})
},
insert: function(query, params, options) {
var id = options.id;
return this.query(query + ' returning ' + id + ' into :returning_into_id', params, options)
},
generateTransactionName: function() {
return 't' + randomstring.generate();
},
begin: function(options) {
var transactionName = options && options.name || this.generateTransactionName();
return this.query("set transaction name '" + transactionName + "'", undefined, {statement: true});
},
connect: function (swormConfig) {
var self = this;
var config = swormConfig.url? parseUrl(swormConfig.url): swormConfig.config;
oracledb.autoCommit = true;
if (config.options) {
Object.keys(config.options).forEach(function (key) {
oracledb[key] = config.options[key];
});
}
function makeConnection() {
if (config.pool === true) {
return connectionPool(oracledb, config, swormConfig).then(function (pool) {
return promisify(function (cb) { pool.getConnection(cb); });
});
} else if (config.pool) {
return promisify(function (cb) { config.pool.getConnection(cb); });
} else {
return promisify(function (cb) { oracledb.getConnection(config, cb); });
}
}
return makeConnection().then(function (connection) {
self.connection = connection;
});
},
close: function () {
var self = this;
if (self.connection) {
return this.outstandingQueries.whenNotExecuting(function () {
return promisify(function (cb) {
self.connection.release(cb);
});
});
} else {
return Promise.resolve();
}
},
insertEmpty: function(meta) {
return 'insert into ' + meta.table + ' (' + meta.id + ') values (default)';
},
outputIdKeys: function (idType) {
return {
returning_into_id: { type: idType || oracledb.NUMBER, dir: oracledb.BIND_OUT }
};
}
};
};
function formatRows(metadata, rows) {
var fields = metadata.map(function (field) {
if (/[a-z]/.test(field.name)) {
return field.name;
} else {
return field.name.toLowerCase();
}
});
if (fields.length > 0) {
var length = rows.length;
var results = new Array(length);
return cooperative.forEach(rows, function(row, index) {
var formattedRow = {};
results[index] = formattedRow;
for (var f = 0; f < fields.length; f++) {
formattedRow[fields[f]] = row[f];
}
}).then(function () {
return results
})
} else {
return Promise.resolve(rows);
}
}
function replaceParameters(query) {
return query.replace(/@([a-z_0-9]+)\b/gi, function (_, paramName) {
return ':' + paramName;
});
}
function parseValue(value) {
var number = Number(value);
if (!isNaN(number)) {
return number;
}
if (value == 'true' || value == 'false') {
return value == 'true';
}
return value;
}
function parseOptions(options) {
var result = {};
Object.keys(options).forEach(function (key) {
result[key] = parseValue(options[key]);
});
return result;
}
function parseUrl(url) {
var u = urlUtils.parse(url, true);
var auth = u.auth? u.auth.split(':'): [];
var options = parseOptions(u.query);
var pool = options.pool;
delete options.pool;
return {
user: auth[0],
password: auth[1],
connectString: u.host + u.pathname,
pool: pool,
options: options
};
}
var connectionPoolCache = {};
module.exports.connectionPoolCache = connectionPoolCache;
function connectionPool(oracledb, config, swormConfig) {
var key = JSON.stringify(config);
var value = connectionPoolCache[key];
if (!value) {
value = connectionPoolCache[key] = promisify(function (cb) {
swormDebug('creating connection pool', redactConfig(swormConfig));
oracledb.createPool(config, cb);
});
}
return value;
}