1 |
|
2 | var Engine, anyDB, dialects, fakeEngine, queries, url;
|
3 |
|
4 | url = require('url');
|
5 |
|
6 | anyDB = require('any-db');
|
7 |
|
8 | queries = require('./queries');
|
9 |
|
10 | dialects = require('./dialects');
|
11 |
|
12 | module.exports = function() {
|
13 | return Engine.create.apply(Engine, arguments);
|
14 | };
|
15 |
|
16 | Engine = (function() {
|
17 | |
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | Engine.create = function(dbUrl, poolOptions) {
|
26 | |
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | var ctor, dialect, driverName, pool;
|
39 | driverName = url.parse(dbUrl).protocol.replace(':', '').split('+').shift();
|
40 | if (driverName === 'fake') {
|
41 | return fakeEngine();
|
42 | }
|
43 | ctor = dialects[driverName];
|
44 | if (!(ctor != null)) {
|
45 | console.error('no such driver', driverName);
|
46 | }
|
47 | dialect = new ctor;
|
48 | pool = anyDB.createPool(dbUrl, poolOptions);
|
49 | return new Engine(driverName, dbUrl, pool, dialect);
|
50 | };
|
51 |
|
52 | function Engine(driver, url, pool, dialect) {
|
53 | this.driver = driver;
|
54 | this.url = url;
|
55 | this.pool = pool;
|
56 | this.dialect = dialect;
|
57 | queries.mixinFactoryMethods(this);
|
58 | }
|
59 |
|
60 | Engine.prototype.query = function(statement, params, callback) {
|
61 | |
62 |
|
63 |
|
64 |
|
65 |
|
66 | var _ref;
|
67 | return (_ref = this.pool).query.apply(_ref, arguments);
|
68 | };
|
69 |
|
70 | Engine.prototype.begin = function(callback) {
|
71 | |
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 | var tx;
|
82 | tx = queries.mixinFactoryMethods(this.pool.begin(callback));
|
83 | tx.engine = this;
|
84 | tx.render = this.dialect.render.bind(this.dialect);
|
85 | return tx;
|
86 | };
|
87 |
|
88 | Engine.prototype.render = function(root) {
|
89 | |
90 |
|
91 |
|
92 | return this.dialect.render(root);
|
93 | };
|
94 |
|
95 | Engine.prototype.close = function() {
|
96 | |
97 |
|
98 |
|
99 | return this.pool.close();
|
100 | };
|
101 |
|
102 | return Engine;
|
103 |
|
104 | })();
|
105 |
|
106 | fakeEngine = function() {
|
107 | |
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 | var dialect, engine;
|
114 | dialect = new dialects.base;
|
115 | engine = {
|
116 | render: dialect.render.bind(dialect),
|
117 | begin: function(cb) {
|
118 | if (cb) {
|
119 | process.nextTick(cb.bind(null, engine));
|
120 | }
|
121 | return engine;
|
122 | },
|
123 | query: function(sql, params, cb) {
|
124 | throw new Error("Cannot query with fakeEngine. Do `gesundheit.defaultEngine = gesundheit.engine(url)` before querying");
|
125 | },
|
126 | close: function() {}
|
127 | };
|
128 | return engine;
|
129 | };
|