Repository navigation
Expand file tree
/
Copy pathORM.js
More file actions
334 lines (280 loc) · 8.41 KB
/
Copy pathORM.js
File metadata and controls
334 lines (280 loc) · 8.41 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
var util = require("util");
var events = require("events");
var path = require("path");
var url = require("url");
var hat = require("hat");
var Query = require("sql-query");
var Model = require("./Model").Model;
var DriverAliases = require("./Drivers/aliases");
var Validators = require("./Validators");
var Settings = require("./Settings");
var Singleton = require("./Singleton");
var ErrorCodes = require("./ErrorCodes");
exports.validators = Validators;
exports.singleton = Singleton;
exports.settings = new Settings.Container(Settings.defaults());
exports.Settings = Settings;
exports.Property = require("./Property");
exports.ErrorCodes = ErrorCodes;
for (var k in Query.Comparators) {
exports[Query.Comparators[k]] = Query[Query.Comparators[k]];
}
exports.express = function () {
return require("./Express").apply(this, arguments);
};
exports.use = function (connection, proto, opts, cb) {
if (DriverAliases[proto]) {
proto = DriverAliases[proto];
}
if (typeof opts == "function") {
cb = opts;
opts = {};
}
try {
var Driver = require("./Drivers/DML/" + proto).Driver;
var driver = new Driver(null, connection, {
debug: (opts.query && opts.query.debug == 'true')
});
return cb(null, new ORM(proto, driver, new Settings.Container(exports.settings.get('*'))));
} catch (ex) {
return cb(ex);
}
};
exports.connect = function (opts, cb) {
if (arguments.length === 0 || !opts) {
return ORM_Error(ErrorCodes.generateError(ErrorCodes.PARAM_MISSMATCH, "CONNECTION_URL_EMPTY"), cb);
}
if (typeof opts == "string") {
if (opts.replace(/\s+/, "").length === 0) {
return ORM_Error(ErrorCodes.generateError(ErrorCodes.PARAM_MISSMATCH, "CONNECTION_URL_EMPTY"), cb);
}
opts = url.parse(opts, true);
}
if (!opts.database) {
// if (!opts.pathname) {
// return cb(new Error("CONNECTION_URL_NO_DATABASE"));
// }
opts.database = (opts.pathname ? opts.pathname.substr(1) : "");
}
if (!opts.protocol) {
return ORM_Error(ErrorCodes.generateError(ErrorCodes.PARAM_MISSMATCH, "CONNECTION_URL_NO_PROTOCOL"), cb);
}
// if (!opts.host) {
// opts.host = opts.hostname = "localhost";
// }
if (opts.auth) {
opts.user = opts.auth.split(":")[0];
opts.password = opts.auth.split(":")[1];
}
if (!opts.hasOwnProperty("user")) {
opts.user = "root";
}
if (!opts.hasOwnProperty("password")) {
opts.password = "";
}
var proto = opts.protocol.replace(/:$/, '');
var db;
if (DriverAliases[proto]) {
proto = DriverAliases[proto];
}
try {
var Driver = require("./Drivers/DML/" + proto).Driver;
var debug = Boolean(extractOption(opts, "debug"));
var pool = Boolean(extractOption(opts, "pool"));
var driver = new Driver(opts, null, {
debug : debug,
pool : pool
});
db = new ORM(proto, driver, new Settings.Container(exports.settings.get('*')));
driver.connect(function (err) {
if (typeof cb == "function") {
if (err) {
return cb(err);
} else {
return cb(null, db);
}
}
db.emit("connect", err, !err ? db : null);
});
} catch (ex) {
if (ex.code == "MODULE_NOT_FOUND" || ex.message.indexOf('find module')) {
return ORM_Error(ErrorCodes.generateError(ErrorCodes.NO_SUPPORT, "CONNECTION_PROTOCOL_NOT_SUPPORTED"), cb);
}
return ORM_Error(ex, cb);
}
return db;
};
function ORM(driver_name, driver, settings) {
this.validators = Validators;
this.settings = settings;
this.driver_name = driver_name;
this.driver = driver;
this.driver.uid = hat();
this.tools = {};
this.models = {};
this.plugins = [];
for (var k in Query.Comparators) {
this.tools[Query.Comparators[k]] = Query[Query.Comparators[k]];
}
events.EventEmitter.call(this);
var onError = function (err) {
if (this.settings.get("connection.reconnect")) {
if (typeof this.driver.reconnect == "undefined") {
return this.emit("error", ErrorCodes.generateError(ErrorCodes.CONNECTION_LOST, "Connection lost - driver does not support reconnection"));
}
this.driver.reconnect(function () {
this.driver.on("error", onError);
}.bind(this));
if (this.listeners("error").length === 0) {
// since user want auto reconnect,
// don't emit without listeners or it will throw
return;
}
}
this.emit("error", err);
}.bind(this);
driver.on("error", onError);
}
util.inherits(ORM, events.EventEmitter);
ORM.prototype.use = function (plugin_const, opts) {
if (typeof plugin_const == "string") {
plugin_const = require(plugin_const);
}
var plugin = new plugin_const(this, opts || {});
if (typeof plugin.define == "function") {
for (var k in this.models) {
plugin.define(this.models[k]);
}
}
this.plugins.push(plugin);
return this;
};
ORM.prototype.define = function (name, properties, opts) {
properties = properties || {};
opts = opts || {};
this.models[name] = new Model({
settings : this.settings,
driver_name : this.driver_name,
driver : this.driver,
table : opts.table || opts.collection || ((this.settings.get("model.namePrefix") || "") + name),
properties : properties,
indexes : opts.indexes || [],
cache : opts.hasOwnProperty("cache") ? opts.cache : this.settings.get("instance.cache"),
id : opts.id || this.settings.get("properties.primary_key"),
keys : opts.keys,
autoSave : opts.hasOwnProperty("autoSave") ? opts.autoSave : this.settings.get("instance.autoSave"),
autoFetch : opts.hasOwnProperty("autoFetch") ? opts.autoFetch : this.settings.get("instance.autoFetch"),
autoFetchLimit : opts.autoFetchLimit || this.settings.get("instance.autoFetchLimit"),
cascadeRemove : opts.hasOwnProperty("cascadeRemove") ? opts.cascadeRemove : this.settings.get("instance.cascadeRemove"),
hooks : opts.hooks || {},
methods : opts.methods || {},
validations : opts.validations || {}
});
for (var i = 0; i < this.plugins.length; i++) {
if (typeof this.plugins[i].define == "function") {
this.plugins[i].define(this.models[name], this);
}
}
return this.models[name];
};
ORM.prototype.ping = function (cb) {
this.driver.ping(cb);
return this;
};
ORM.prototype.close = function (cb) {
this.driver.close(cb);
return this;
};
ORM.prototype.load = function (file, cb) {
var cwd = process.cwd();
var err = new Error();
var tmp = err.stack.split(/\r?\n/)[2], m;
if ((m = tmp.match(/^\s*at\s+(.+):\d+:\d+$/)) !== null) {
cwd = path.dirname(m[1]);
} else if ((m = tmp.match(/^\s*at\s+module\.exports\s+\((.+?)\)/)) !== null) {
cwd = path.dirname(m[1]);
} else if ((m = tmp.match(/^\s*at\s+.+\s+\((.+):\d+:\d+\)$/)) !== null) {
cwd = path.dirname(m[1]);
}
if (file[0] != path.sep) {
file = cwd + "/" + file;
}
if (file.substr(-1) == path.sep) {
file += "index";
}
try {
return require(file)(this, cb);
} catch (ex) {
return cb(ex);
}
};
ORM.prototype.sync = function (cb) {
var modelIds = Object.keys(this.models);
var syncNext = function () {
if (modelIds.length === 0) {
return cb();
}
var modelId = modelIds.shift();
this.models[modelId].sync(function (err) {
if (err) {
err.model = modelId;
return cb(err);
}
return syncNext();
});
}.bind(this);
if (arguments.length === 0) {
cb = function () {};
}
syncNext();
return this;
};
ORM.prototype.serial = function () {
var chains = Array.prototype.slice.apply(arguments);
return {
get: function (cb) {
var params = [];
var getNext = function () {
if (params.length === chains.length) {
params.unshift(null);
return cb.apply(null, params);
}
chains[params.length].run(function (err, instances) {
if (err) {
params.unshift(err);
return cb.apply(null, params);
}
params.push(instances);
return getNext();
});
};
getNext();
return this;
}
};
};
function ORM_Error(err, cb) {
var Emitter = new events.EventEmitter();
Emitter.use = Emitter.define = Emitter.sync = Emitter.load = function () {};
if (typeof cb == "function") {
cb(err);
}
process.nextTick(function () {
Emitter.emit("connect", err);
});
return Emitter;
}
function extractOption(opts, key) {
if (!opts.query || !opts.query.hasOwnProperty(key)) {
return null;
}
var opt = opts.query[key];
delete opts.query[key];
if (opts.href) {
opts.href = opts.href.replace(new RegExp(key + "=[^&]+&?"), "");
}
if (opts.search) {
opts.search = opts.search.replace(new RegExp(key + "=[^&]+&?"), "");
}
return opt;
}