-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathdata-source-definition.js
More file actions
474 lines (404 loc) · 13.6 KB
/
Copy pathdata-source-definition.js
File metadata and controls
474 lines (404 loc) · 13.6 KB
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
// Copyright IBM Corp. 2015,2019. All Rights Reserved.
// Node module: loopback-workspace
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
const g = require('strong-globalize')();
const app = require('../../server/server');
module.exports = function(DataSourceDefinition) {
app.once('ready', function() {
ready(DataSourceDefinition);
});
};
function ready(DataSourceDefinition) {
const async = require('async');
const ModelDefinition = app.models.ModelDefinition;
const ModelConfig = app.models.ModelConfig;
const ModelProperty = app.models.ModelProperty;
const fork = require('child_process').fork;
const loopback = require('loopback');
const debug = require('debug')('workspace:data-source-definition');
const ConfigFile = app.models.ConfigFile;
/*
TODOs
- add a flag indicating if discover is supported
*/
/**
* Defines a `DataSource` configuration.
* @class DataSourceDefinition
* @inherits Definition
*/
/**
* - `name` must be unique per `Facet`
* - `name` and `connector` are required
* - `facetName` is required and must refer to an existing facet
*
* @header Property Validation
*/
DataSourceDefinition.validatesUniquenessOf('name', {scopedTo: ['facetName']});
DataSourceDefinition.validatesPresenceOf('name', 'connector');
DataSourceDefinition.validatesPresenceOf('facetName');
/**
* Test the datasource definition connection.
*
* @callback {Function} callback
* @param {Error} err A connection or other error
* @param {Boolean} success `true` if the connection was established
*/
DataSourceDefinition.prototype.testConnection = function(cb) {
this.invokeMethodInWorkspace('ping', function(err) {
if (!err) {
return cb(null, true);
}
if (err.origin === 'invoke') {
// report `ping` errors as a 200 result with error details, not a 500
cb(null, false, {
message: err.message,
code: err.code,
details: err.details,
stack: err.stack,
});
} else {
cb(err);
}
});
};
loopback.remoteMethod(DataSourceDefinition.prototype.testConnection, {
returns: [
{arg: 'status', type: 'boolean'},
{arg: 'error', type: 'object'},
],
});
/**
* Test the datasource connection (static version).
*
* @deprecated Use the prototype version.
*
* @param {Object} data DataSourceDefinition
* @callback {Function} callback
* @param {Error} err A connection or other error
* @param {Boolean} success `true` if the connection was established
*/
DataSourceDefinition.testConnection = function(data, cb) {
// A legacy implementation that runs the test in loopback-workspace process
try {
const dataSource = new DataSourceDefinition(data).toDataSource();
dataSource.ping(function(err) {
cb(err, !err);
});
} catch (err) {
debug('Cannot connect to the data source.\nData: %j\nError: %s', data, err);
// NOTE(bajtos) juggler ignores unknown connector and let the application
// crash later, when a method of undefined connector is called
// We have to build a useful error message ourselves
return cb(
new Error(g.f('Cannot connect to the data source.' +
' Ensure the configuration is valid and the connector is installed.')),
);
}
};
DataSourceDefinition.remoteMethod('testConnection', {
accepts: {
arg: 'data', type: 'DataSourceDefinition', http: {source: 'body'},
},
returns: {
arg: 'status', type: 'boolean',
},
http: {verb: 'POST'},
});
/**
* Discover the model definition by table name from this data source. Use the `name`
* provided by items from returned from `DataSourceDefinition.getSchema()`.
*
* @param {String} modelName The model name (usually from `DataSourceDefinition.getSchema()`.
* @options {Object} [options] Options; see below.
* @property {String} owner|schema Database owner or schema name.
* @property {Boolean} relations True if relations (primary key/foreign key) are navigated; false otherwise.
* @property {Boolean} all True if all owners are included; false otherwise.
* @property {Boolean} views True if views are included; false otherwise.
*/
DataSourceDefinition.prototype.discoverModelDefinition = function(name, options, cb) {
const self = this;
cb = arguments[arguments.length - 1];
if (typeof options === 'function') {
cb = options;
options = undefined;
}
if (typeof cb !== 'function') {
cb = function getSchemaCallback(err) {
if (err) console.error(err);
};
}
if (!options) options = {};
this._setDefaultSchema(options);
this.invokeMethodInWorkspace('discoverSchema', name, options, function(err, result) {
if (err) return cb(err);
if (result.base || result.options.base)
return cb(null, result);
self.getDefaultBaseModel(function(err, baseModel) {
if (err) return cb(err);
if (baseModel)
result.options.base = baseModel;
cb(null, result);
});
});
};
loopback.remoteMethod(DataSourceDefinition.prototype.discoverModelDefinition, {
accepts: [{
arg: 'tableName', type: 'string', required: true,
}, {
arg: 'options', type: 'object',
}],
returns: {arg: 'status', type: 'boolean'},
});
DataSourceDefinition.prototype.getDefaultBaseModel = function(cb) {
const connectorName = this.connector;
DataSourceDefinition.app.models.Workspace.listAvailableConnectors(
function(err, list) {
if (err) return cb(err);
const meta = list.filter(function(c) {
return c.name === connectorName;
})[0];
return cb(null, meta && meta.baseModel);
},
);
};
/**
* Get a list of table / collection names, owners and types.
*
* @param {Object} options The options
* @param {Function} Callback function. Optional.
* @options {Object} options Discovery options. See below.
* @property {Boolean} all If true, discover all models; if false, discover only
* models owned by the current user.
* @property {Boolean} views If true, include views; if false, only tables.
* @property {Number} limit Page size
* @property {Number} offset Starting index
* @callback {Function} callback
* @param {Error} err
* @param {ModelDefinition[]} models An array of model definitions
*/
DataSourceDefinition.prototype.getSchema = function(options, cb) {
cb = arguments[arguments.length - 1];
if (typeof options === 'function') {
cb = options;
options = undefined;
}
if (typeof cb !== 'function') {
cb = function getSchemaCallback(err) {
if (err) console.error(err);
};
}
if (!options) options = {};
this._setDefaultSchema(options);
this.invokeMethodInWorkspace('discoverModelDefinitions', options, cb);
};
loopback.remoteMethod(DataSourceDefinition.prototype.getSchema, {
accepts: {arg: 'options', type: 'object'},
returns: {arg: 'models', type: 'array'},
});
DataSourceDefinition.prototype._setDefaultSchema = function(options) {
if (options && typeof options === 'object' && !options.schema) {
switch (this.connector) {
case 'loopback-connector-oracle':
case 'oracle':
options.schema = this.username;
break;
case 'loopback-connector-mysql':
case 'mysql':
options.schema = this.database;
break;
case 'loopback-connector-postgresql':
case 'postgresql':
options.schema = 'public';
break;
case 'loopback-connector-mssql':
case 'mssql':
options.schema = 'dbo';
break;
}
}
};
/**
* Run a migration on the data source. Creates indexes, tables, collections, etc.
*
* **NOTE: this will destroy any existing data**
*
* @param {string} modelName
* @callback {Function} callback
* @param {Error} err
* @param {boolean} success
*/
DataSourceDefinition.prototype.automigrate = function(modelName, cb) {
this.invokeMethodInWorkspace('automigrate', modelName, cb);
};
loopback.remoteMethod(DataSourceDefinition.prototype.automigrate, {
accepts: {arg: 'modelName', type: 'string'},
returns: {arg: 'success', type: 'boolean'},
http: {verb: 'POST'},
});
/**
* Update existing tables / collections.
*
* @param {string} modelName
* @callback {Function} callback
* @param {Error} err
* @param {boolean} success
*/
DataSourceDefinition.prototype.autoupdate = function(modelName, cb) {
this.invokeMethodInWorkspace('autoupdate', modelName, cb);
};
loopback.remoteMethod(DataSourceDefinition.prototype.autoupdate, {
accepts: {arg: 'modelName', type: 'string'},
returns: {arg: 'success', type: 'boolean'},
http: {verb: 'POST'},
});
DataSourceDefinition.prototype.invokeMethodInWorkspace = function(methodName) {
// TODO(bajtos) We should ensure there is never more than one instance
// of this code running at any given time.
let isDone = false;
const self = this;
const args = Array.prototype.slice.call(arguments, 0);
let cb;
const stdErrs = [];
const invokePath = require.resolve('../../bin/datasource-invoke');
// remove method name
args.shift();
if (typeof args[args.length - 1] === 'function') {
cb = args.pop();
} else {
cb = function invokeComplete(err) {
if (err) console.error(err);
};
}
const child = fork(invokePath, [], {silent: true});
child.stdout.pipe(process.stdout);
// handle the callback message
child.once('message', function(msg) {
const err = msg.error;
if (err) {
return done(missingConnector(err) || err);
}
done.apply(self, msg.callbackArgs);
child.kill();
});
child.stderr.on('data', storeErrors);
child.on('exit', function(code) {
if (code > 0) {
done(new Error(stdErrs.join('')));
}
});
// send the args as a message to the child
child.send({
dir: ConfigFile.getWorkspaceDir(),
dataSourceName: this.name,
methodName: methodName,
args: args,
});
function done(err) {
if (isDone && err) {
g.error('Error calling %s after callback!', methodName);
console.error(err);
return;
}
child.stderr.removeListener('data', storeErrors);
cb.apply(self, arguments);
isDone = true;
}
function storeErrors(buf) {
stdErrs.push(buf.toString());
}
function missingConnector(err) {
if (err == null || typeof err.message !== 'string') {
return undefined;
}
const match = err.message.match(
/LoopBack connector "(.*)" is not installed/,
);
if (match && match[1] === self.connector) {
const msg = g.f('Connector "%s" is not installed.', self.connector);
err = new Error(msg);
err.name = 'InvocationError';
err.code = 'ER_INVALID_CONNECTOR';
return err;
}
return undefined;
}
};
/**
* Create a `loopback.DataSource` object from the `DataSourceDefinition`.
*
* @returns {DataSource}
*/
DataSourceDefinition.prototype.toDataSource = function() {
return loopback.createDataSource(this.name, this);
};
/**
* Create a `ModelDefinition` with the appropriate set of `ModelProperties` and
* `ModelConfig` using the given `discoveredDef` object.
*
* @param {Object} discoveredDef The result of `dataSource.discoverModelDefinition()`.
* @callback {Function} callback
* @param {Error} err
* @param {String} id The created `ModelDefinition` id
*/
DataSourceDefinition.prototype.createModel = function(discoveredDef, cb) {
const dataSourceDef = this;
const properties = [];
const propertyNames = Object.keys(discoveredDef.properties);
const options = discoveredDef.options;
let modelDefinition = {};
let modelDefinitionId;
// use common facet by default
modelDefinition.facetName = 'common';
modelDefinition.name = discoveredDef.name;
// merge options
Object.keys(options).forEach(function(option) {
modelDefinition[option] = options[option];
});
// convert properties object to array
propertyNames.forEach(function(propertyName) {
const property = discoveredDef.properties[propertyName];
property.name = propertyName;
properties.push(property);
});
async.series([
createModelDefinition,
createProperties,
createModelConfig,
], function(err) {
if (err) return cb(err);
cb(null, modelDefinition.id);
});
function createModelDefinition(cb) {
ModelDefinition.create(modelDefinition, function(err, def) {
if (err) return cb(err);
modelDefinition = def;
cb();
});
}
function createProperties(cb) {
async.each(properties, function(property, cb) {
const data = ModelProperty.getDataFromConfig(property);
modelDefinition.properties.create(data, cb);
}, cb);
}
function createModelConfig(cb) {
if (modelDefinition.public === undefined) {
modelDefinition.public = true;
}
ModelConfig.create({
dataSource: dataSourceDef.name,
facetName: dataSourceDef.facetName,
name: modelDefinition.name,
public: modelDefinition.public,
}, cb);
}
};
loopback.remoteMethod(DataSourceDefinition.prototype.createModel, {
accepts: {arg: 'discoveredDef', type: 'object',
description: 'usually the result of discoverModelDefinition'},
returns: {arg: 'modelDefinitionId', type: 'string'},
http: {verb: 'POST'},
});
}