-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
508 lines (407 loc) · 12.2 KB
/
index.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
const Stream = require('stream')
const util = require('util')
const Promise = require('bluebird')
const map = require('map-stream')
const xtend = require('xtend')
const create = require('./lib/create')
const hasCallback = require('./lib/has-callback')
const callbackResolver = require('./lib/callback-resolver')
const fmt = util.format.bind(util)
const dbProto = {}
const tableProto = {}
dbProto.close = function close(callback) {
return this.driver.close(this.connection, callback)
}
dbProto.table = function table(name, definition) {
if (definition)
return this.registerTable.apply(this, arguments)
const tableDefinition = this.tables[name]
if (!tableDefinition)
throw new Error(fmt('No table registered with the name `%s`', name))
return tableDefinition
}
dbProto.registerTable = function registerTable(name, def) {
const fields = def.fields || []
const primaryKey = def.primaryKey || 'id'
if (fields.indexOf(primaryKey) === -1)
fields.unshift(primaryKey)
if (!def.hasOwnProperty('constructor')) {
def.constructor = function createRow (data) {
return create(table.row, data)
}
}
const table = create(tableProto, {
table: def.tableName || name,
primaryKey: primaryKey,
fields: fields,
methods: def.methods || {},
row: def.methods || {},
constructor: def.constructor,
relationships: def.relationships || {},
db: this,
})
this.tables[name] = table
return table
}
tableProto.put = function put(row, opts, callback) {
var resolver = Promise.defer()
opts = opts || {}
if (hasCallback(arguments)) {
if (typeof opts == 'function') {
callback = opts
opts = {}
}
resolver = callbackResolver(callback)
}
const table = this.table
const primaryKey = this.primaryKey
var uniqueKey
if (opts.uniqueKey) {
uniqueKey = typeof opts.uniqueKey === 'string'
? [opts.uniqueKey]
: opts.uniqueKey
}
const driver = this.db.driver
const insertSql = driver.insertSql(table, row)
const tryUpdate = primaryKey in row || uniqueKey
const meta = { row: row, sql: null, insertId: null }
const query = this.db.query(insertSql, function (err, result) {
if (err) {
if (tryUpdate && driver.putShouldUpdate(err, opts)) {
const keys = uniqueKey ? uniqueKey : [primaryKey]
const cond = keys.reduce(function (cond, key) {
cond[key] = row[key]
return cond
}, {})
return this.update(row, cond, resolver.callback)
}
return resolver.reject(err)
}
meta.sql = insertSql
meta.insertId = result.insertId
return resolver.resolve(meta)
}.bind(this))
return resolver.promise
}
tableProto.update = function update(row, conditions, callback) {
var resolver = Promise.defer()
conditions = conditions || {}
if (hasCallback(arguments)) {
if (typeof conditions == 'function') {
callback = conditions
conditions = {}
}
resolver = callbackResolver(callback)
}
const table = this.table
const driver = this.db.driver
const updateSql = driver.updateSql(table, row, conditions)
const query = this.db.query(updateSql, handleResult)
const meta = {
row: row,
sql: updateSql,
affectedRows: null
}
function handleResult(err, result) {
if (err) { return resolver.reject(err) }
meta.affectedRows = result.affectedRows
return resolver.resolve(meta)
}
return resolver.promise
}
tableProto.get = function get(cnd, opts, callback) {
var resolver = Promise.defer()
cnd = cnd || {}
opts = opts || {}
if (hasCallback(arguments)) {
if (typeof opts == 'function') {
callback = opts
opts = {}
}
if (typeof cnd == 'function') {
callback = cnd
cnd = {}
opts = {}
}
resolver = callbackResolver(callback)
}
const self = this;
const RowClass = self.constructor
const driver = self.db.driver
const table = self.table
const tableCache = self.db.tables
const relationships = buildRelationships(self, opts.relationships, opts.relationshipsDepth)
var error = {}
const selectSql = driver.selectSql({
db: self.db,
table: table,
tables: tableCache,
relationships: relationships,
fields: self.fields,
conditions: cnd,
limit: opts.limit,
include: opts.include,
exclude: opts.exclude,
page: opts.page,
order: opts.sort || opts.order || opts.orderBy,
})
if (typeof selectSql == 'object' && selectSql.name == 'RangeError') {
error = selectSql
return setImmediate(resolver.reject.bind(null, error))
}
self.db.query(selectSql, opts.single ? singleRow : manyRows)
const hydrOpts = {
table: table,
relationships: relationships,
tableCache: tableCache,
}
function singleRow(err, rows) {
if (err) return resolver.reject(err)
if (!rows.length) return resolver.resolve()
const singleton = rows[0]
if (!singleton)
return resolver.resolve()
driver.hydrateRow(singleton, hydrOpts, function (err, result) {
if (err) return resolver.reject(err)
return resolver.resolve(new RowClass(result))
})
}
function manyRows(err, rows) {
if (err) return resolver.reject(err)
driver.hydrateRows(rows, hydrOpts, function (err, rows) {
if (err) return resolver.reject(err)
const hydratedRows = rows.map(function (row) {
return new RowClass(row)
})
if (!opts.includeTotal)
return resolver.resolve(hydratedRows)
const countSql = ''
+ 'SELECT COUNT(*) AS `total` FROM $table '
+ driver.whereSql(table, cnd)
self.getOne(countSql, function (err, data) {
if (err) return resolver.reject(err)
data.rows = hydratedRows
return resolver.resolve(data)
})
})
}
if (opts.debug)
console.error(selectSql)
return resolver.promise
}
tableProto.getAll = function getAll(opts, callback) {
return this.get({}, opts, callback)
}
tableProto.getOne = function getOne(cnd, opts, callback) {
if (typeof opts == 'function') {
callback = opts
opts = {}
}
const singularOpts = { limit: 1, single: true }
return this.get(cnd, xtend(opts, singularOpts), callback)
}
tableProto.del = function del(cnd, opts, callback) {
var resolver = Promise.defer()
if (hasCallback(arguments)) {
if (typeof opts == 'function') {
callback = opts
opts = null
}
resolver = callbackResolver(callback)
}
opts = opts || {}
const query = this.db.query
const driver = this.db.driver
const table = this.table
const deleteSql = driver.deleteSql({
table: table,
conditions: cnd,
limit: opts.limit
})
if (opts.debug)
console.error(deleteSql)
// the callback for query generally has an arity of 3, we only want an
// arity of 2, so we have to do this little dance.
query(deleteSql, function (err, success) {
resolver.callback(err, success)
})
return resolver.promise
}
tableProto.createReadStream = function createReadStream(conditions, opts) {
opts = opts || {}
const conn = this.db.connection
const driver = this.db.driver
const fields = this.fields
const table = this.table
const relationships = buildRelationships(this, opts.relationships, opts.relationshipsDepth)
const selectSql = driver.selectSql({
db: this.db,
table: table,
tables: this.db.tables,
fields: fields,
conditions: conditions,
limit: opts.limit,
page: opts.page,
relationships: relationships,
include: opts.include,
exclude: opts.exclude,
order: opts.order || opts.orderBy,
})
const tableCache = this.db.tables
const queryStream = this.db.queryStream(selectSql, {
rowPrototype: this.row,
relationships: relationships,
tableCache: this.db.tables,
table: table,
})
if (opts.debug)
console.error(selectSql)
return queryStream
}
tableProto.createKeyStream = function createKeyStream(conditions, opts) {
const primaryKey = this.primaryKey
opts = xtend(opts, {
orderBy: opts.orderBy || primaryKey,
include: [ primaryKey ]
})
const keyStream = this.createReadStream(conditions, opts)
.pipe(map(function (row, next) {
return next(null, row[primaryKey])
}))
return keyStream
}
tableProto.createWriteStream = function createWriteStream(opts) {
opts = opts || {}
const ignoreDupes = opts.ignoreDupes
const conn = this.db.connection
const table = this.table
const stream = new Stream()
const emit = stream.emit.bind(stream)
const put = this.put.bind(this)
var waiting = 0
var ending = false
function done() {
['finish', 'close', 'end'].forEach(emit)
}
function drain() {
waiting -= 1
emit('drain')
if (ending && waiting <= 0)
return done()
}
stream.readable = true
stream.writable = true
stream.write = function write(row, callback) {
waiting += 1
put(row, function handleResult(err, meta) {
if (err) {
if (ignoreDupes) {
emit('dupe', row)
return drain()
}
if (callback) { callback(err) }
emit('error', err, meta)
return drain()
}
emit('meta', meta)
emit('data', row)
if (callback && typeof callback == 'function')
callback(null, meta)
return drain()
})
return false;
}
stream.end = function end(row, callback) {
stream.readable = false
if (typeof row == 'function') {
callback = row
row = null
}
if (callback)
stream.on('end', callback)
if (row) {
stream.write(row)
return stream.end()
}
if (waiting > 0)
ending = true
else
done()
}
return stream
}
const base = module.exports = {
connect: function connect(options, callback) {
const driver = getDriver(options.driver)
const connection = driver.connect(options, callback)
return create(dbProto, {
connection: connection,
query: driver.getQueryFn(connection),
queryStream: driver.getStreamFn(connection),
tables: {},
driver: driver,
})
}
}
function getDriver(name) {
const drivers = require('./lib/drivers')
const prototype = require('./lib/drivers/prototype')
const implementation = drivers[name || 'mysql']()
return create(prototype, implementation)
}
function buildRelationships(instance, relationships, depth) {
if (typeof relationships == 'boolean' &&
relationships === true) {
// Use all relationships if `relationships === true`
relationships = instance.relationships
} else if (typeof relationships == 'number') {
// Use all relationships
depth = relationships
relationships = instance.relationships
} else if (relationships instanceof Array) {
// Use subset of relationships if array of keys given
relationships = relationships.reduce(function (r, relation) {
if (instance.relationships.hasOwnProperty(relation))
r[relation] = instance.relationships[relation]
return r
}, {})
} else if (instance.relationships.hasOwnProperty(relationships)) {
// Use single relationship if key given
var relation = relationships
relationships = {}
relationships[relation] = instance.relationships[relation]
} else {
// Use given relationships, or empty if not provided
relationships = relationships || {}
}
return _buildRelationships(instance.table, relationships, depth, instance.db.tables)
}
function _buildRelationships (table, base, depth, tableCache, history) {
if (depth === true)
depth = Infinity
depth = depth === Infinity || depth < 0 ? Infinity : parseInt(depth, 10)
if (isNaN(depth) || !depth)
return base
history = history || []
return Object.keys(base).reduce(function (relationships, relation) {
const relationship = base[relation]
const key = [table, relationship.foreign.table].join(':')
if (history.indexOf(key) > -1)
return relationships
history.push(key)
relationship.foreign.as = relationship.foreign.as || relation
const foreignTable = tableCache[relationship.foreign.table];
if (foreignTable && (depth - 1))
relationship.relationships =
_buildRelationships(
relationship.foreign.table,
foreignTable.relationships,
depth - 1,
tableCache,
history
)
relationships = relationships || {}
relationships[relation] = relationship
return relationships
}, undefined)
}